Parse Nested XML with xDocument

梦想与她 提交于 2020-01-06 03:36:07

问题


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



来源:https://stackoverflow.com/questions/15126644/parse-nested-xml-with-xdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!