简体   繁体   中英

Is this correct way to Parse inner element of XML by LINQ in C#

Always confused with LINQ to XML. I would like to extract emails as IEnumerable from the following XML.

   String xml =@"<?xml version=""1.0"" encoding=""utf-8""?>
                   <people>
                     <person firstname=""John"" lastname=""doe"">
                       <contactdetails>
                          <emailaddress>john@unknown.com</emailaddress>
                       </contactdetails>
                     </person> 
                     <person firstname=""Jane"" lastname=""doe"">
                       <contactdetails>
                          <emailaddress>jane@unknown.com</emailaddress>
                           <phonenumber>001122334455</phonenumber>
                         </contactdetails>
                     </person>
                   </people>";

After some trials I found the following code works, but I don't like to use ElementAt(0).Value (normally I don't see in other example code). What would be the best way to use LINQ here?

XDocument doc = XDocument.Parse(xml);
var emails = from p in doc.Descendants("person")
where p.Descendants("emailaddress").Any()
let email =  (string)p.Descendants("emailaddress").ElementAt(0).Value                                      
select email;

get all emails from xml

var e_mailsAll = doc.Descendants("person")
        .Descendants("emailaddress")
        .Select(x=>x.Value);

get first email of each person, if someone has more than 1

var e_mailsFirst = doc.Descendants("person")
        .Select(x=>x.Descendants("emailaddress").FirstOrDefault())
        .Where(x=>x!=null)
        .Select(x=>x.Value);

You can use XPathSelectElements in order to extract IEnumerable<XElement> using XPath:

string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
   <people>
     <person firstname=""John"" lastname=""doe"">
       <contactdetails>
          <emailaddress>john@unknown.com</emailaddress>
       </contactdetails>
     </person> 
     <person firstname=""Jane"" lastname=""doe"">
       <contactdetails>
          <emailaddress>jane@unknown.com</emailaddress>
           <phonenumber>001122334455</phonenumber>
         </contactdetails>
     </person>
   </people>";

IEnumerable<XElement> elements = XDocument 
    .Parse(xml)
    .XPathSelectElements("people/person/contactdetails/emailaddress");

Then, you will be able to use LINQ Select in order to extract an array of emails:

string[] elements = XDocument 
    .Parse(xml)
    .XPathSelectElements("people/person/contactdetails/emailaddress")
    .Select(x => x.Value)
    .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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