2011-06-07 140 views
4

我想用C#解析一个复杂的XML,我使用Linq来完成它。基本上,我做的到服务器的请求,我得到XML,这是代码:用C解析复杂的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> 

如何访问到性能测试:例如link_id?

谢谢!

+0

它看起来像'测试'是一个命名空间?如果是这样,XName对象应该帮助你。 http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.aspx – 2011-06-07 22:22:40

+0

@伊万,因为这是行不通的。 – svick 2011-06-07 23:35:26

回答

8

目前你的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() 
          } 
4

为了写一篇关于XML是在 命名空间,你必须使用的XName对象 具有正确查询命名空间。对于 C#中,最常见的方法是 初始化使用 字符串包含URI的的XNamespace,然后使用 加法运算符重载 与当地 名称结合的命名空间。

要检索link_id元素,你需要声明和使用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了解更多信息。