Parse Nested XML with xDocument

2019-08-04 00:09发布

问题:

I have an XML format of this structure (the real world example is horrendously long and complicated, but this should illustrate it):

<document>    <post>
      <author>Bill Smith</author>
      <subject>Test Article</subject>
      <dates>
          <uploaded>some date</uploaded>
          <published>some date</published>
      </dates>
    </post>
    <post>
      <author>Bill Smith</author>
      <subject>Test Article</subject>
      <dates>
          <uploaded>some date</uploaded>
          <published>some date</published>
      </dates>
    </post>  </document>

I have wrote a simple query to pull out each of the posts. I can get the author and subject fine, but I don't know how to drill down into the dates part to pull out the published bit.

Thanks

回答1:

You can use the following LINQ to get the first "published" element.

    XDocument document = XDocument.Load(@"D:\XMLFile1.xml", LoadOptions.None);
    XElement element = document
    .Descendants("document")
            .Descendants("post")
    .Descendants("dates")
    .Descendants("published")
    .First();
string publishedDate = element.Value;

You can give any expressions as parameter to the 'Descendants' method. If you have xml as a string, you can use the following to read it into an XDocument

XDocument.Parse();

Please remember to check for nulls!! :-)