Parse Nested XML with xDocument

2019-08-03 23:21发布

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条回答
Animai°情兽
2楼-- · 2019-08-04 00:05

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!! :-)

查看更多
登录 后发表回答