使用C#解析复杂的XML

Parsing complex XML with C#

我正在尝试使用C#解析复杂的XML,我正在使用Linq来做到这一点。基本上,我正在向服务器发送请求,并且获得XML,这是代码:

1
2
3
4
5
6
7
8
9
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结构:

1
2
3
4
5
6
<item>
  <test:link_id>1282570</test:link_id>
  <test:user>SLAYERTANIC</test:user>
  aaa
  <description>aaa</description>
</item>

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

谢谢!


由于未声明test命名空间,当前您的XML无效,您可以这样声明:

1
2
3
4
5
6
<item xmlns:test="http://foo.bar">
  <test:link_id>1282570</test:link_id>
  <test:user>SLAYERTANIC</test:user>
  aaa
  <description>aaa</description>
</item>

具有此功能,您可以使用XNamespace使用正确的名称空间来限定所需的XML元素:

1
2
3
4
5
6
7
8
9
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()
                            }


To write a query on XML that is in a
namespace, you must use XName objects
that have the correct namespace. For
C#, the most common approach is to
initialize an XNamespace using a
string that contains the URI, then use
the addition operator overload to
combine the namespace with the local
name.

要检索link_id元素的值,您将需要声明并使用XML名称空间作为test:link元素。

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

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

1
2
3
4
5
6
7
8
9
10
11
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()                            
  }

有关更多信息,请参见C#中的XNamespace和命名空间,以及如何:在命名空间中的XML上编写查询。