简体   繁体   English

linq to xml:如何在C#中的元素中获取标签的值

[英]linq to xml: How to get value of a tag in an element in C#

I have following xml data. 我有以下xml数据。

<?xml version="1.0" encoding="utf-8" ?>
<mail>
  <id>signUpConfirmation</id>
  <subject>Activation</subject>
  <body>
Hi, You account is activated \nRegards
</body>
</mail>

I need to read value from <body> tag depending on id I pass. 我需要根据传递的id从<body>标记读取值。

This is what I have tried 这就是我尝试过的

var xml = File.ReadAllText("C:\\Users\\DELL\\Documents\\Visual Studio 2012\\Projects\\Website\\Website\\Files\\Mails.xml");

var str = XElement.Parse(xml);
var result = from mail in str.Elements("mail")
             where (string)mail.Element("id") == "signUpConfirmation"
             select (string)mail.Element("body");
log.Debug("mail data:" + result.First());

I get error : 我收到错误消息:

Sequence contains no elements. 序列不包含任何元素。

Also, I want to access the value of id tag as well in the same query. 另外,我也想在同一查询中访问id标签的值。

You have a couple of problems: 您有几个问题:

  1. The id and body are not attributes but elements so you need to use the .Elements idbody不是属性而是元素,因此您需要使用.Elements
  2. You are using the XElement to parse the xml. 您正在使用XElement解析xml。 It will start from the first element which is mail and then you are looking for child elements of it with the name of mail - which non exist. 它将从第一个元素mail ,然后您要查找其名称为mail子元素-不存在。 Use XDocument . 使用XDocument

Code: 码:

var result = (from mail in XDocument.Load("data.xml").Descendants("mail")
              where mail.Element("id").Value == "signUpConfirmation"
              select new {
                  Body = mail.Element("body").Value,
                  Subject = mail.Element("subject").Value
              }).ToList();
var str = XDocument.Parse("<?xml version=\"1.0\" encoding=\"utf-8\" ?><mail>  <id>signUpConfirmation</id>  <subject>Activation</subject>  <body>Hi, You account is activated \nRegards</body></mail>");

var result = from mail in str.Elements("mail")
where (string)mail.Element("id") == "signUpConfirmation"
select mail.Element("body");
result.FirstOrDefault();

Here is the code that work. 这是起作用的代码。

XDocument XDocument

instead of 代替

XElement X元素

End .Element as @DKR said. 以@DKR的形式结束.Element。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM