DKR DKR - 1 month ago 12
C# Question

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

I have following xml data.

<?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 tag depending on id I pass.

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 value of id tag as well in same query.

Please help.

Thanks

Answer

You have a couple of problems:

  1. The id and body are not attributes but elements so you need to use the .Elements
  2. You are using the XElement to parse the 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. Use 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();
Comments