2011-06-07 143 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瞭解更多信息。