使用xDocument解析嵌套的XML [英] Parse Nested XML with xDocument

查看:110
本文介绍了使用xDocument解析嵌套的XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种结构的XML格式(现实世界中的例子冗长而复杂,但这应该可以说明这一点):

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.

谢谢

推荐答案

您可以使用以下LINQ来获取第一个已发布"元素.

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;

您可以将任何表达式作为后代"方法的参数. 如果您将xml作为字符串,则可以使用以下内容将其读入XDocument

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

这篇关于使用xDocument解析嵌套的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆