【问题标题】:Parsing complex XML with C#使用 C# 解析复杂的 XML
【发布时间】:2011-06-08 06:44:56
【问题描述】:

我正在尝试使用 C# 解析复杂的 XML,我正在使用 Linq 来执行此操作。基本上,我正在向服务器发出请求并获得 XML,这是代码:

XElement xdoc = XElement.Parse(e.Result);
this.newsList.ItemsSource = 
  from item in xdoc.Descendants("item")
  select new ArticlesItem
  {
    //Image = item.Element("image").Element("url").Value,
    Title = item.Element("title").Value,
    Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()
  }

这是 XML 结构:

<item>
  <test:link_id>1282570</test:link_id>
  <test:user>SLAYERTANIC</test:user>
  <title>aaa</title>
  <description>aaa</description>
</item>

例如,我如何访问属性 test:link_id?

谢谢!

【问题讨论】:

标签: c# xml windows-phone-7


【解决方案1】:

目前您的 XML 无效,因为 test 命名空间未声明,您可以这样声明:

<item xmlns:test="http://foo.bar">
  <test:link_id>1282570</test:link_id>
  <test:user>SLAYERTANIC</test:user>
  <title>aaa</title>
  <description>aaa</description>
</item>

有了这个,您可以使用XNamespace 来使用正确的命名空间来限定您想要的 XML 元素:

XElement xdoc = XElement.Parse(e.Result);
XNamespace test = "http://foo.bar";
this.newsList.ItemsSource = from item in xdoc.Descendants("item")
                            select new ArticlesItem
                            {
                                LinkID = item.Element(test + "link_id").Value,
                                Title = item.Element("title").Value,
                                Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()
                            }

【讨论】:

    【解决方案2】:

    在 XML 上编写查询 命名空间,您必须使用 XName 对象 具有正确的命名空间。为了 C#,最常见的方法是 使用 a 初始化 XNamespace 包含 URI 的字符串,然后使用 加法运算符重载到 将命名空间与本地结合起来 名字。

    要检索 link_id 元素的值,您需要为 test:link 元素声明并使用 XML namespace

    由于您没有在示例 XML 中显示名称空间声明,我将假设它在 XML 文档中的其他位置声明。您需要在 XML 中找到命名空间声明(类似于 xmlns:test="http://schema.example.org" ),该声明通常在 XML 文档的根目录中声明。

    知道了这一点后,你可以执行以下操作来检索link_id元素的值:

    XElement xdoc = XElement.Parse(e.Result);
    
    XNamespace testNamespace = "http://schema.example.org";
    
    this.newsList.ItemsSource = from item in xdoc.Descendants("item")
      select new ArticlesItem
      {
        Title       = item.Element("title").Value,
        Link        = item.Element(testNamespace + "link_id").Value,
        Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()                            
      }
    

    有关详细信息,请参阅 XNamespaceNamespaces in C#How to: Write Queries on XML in Namespaces

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      相关资源
      最近更新 更多