2016-12-06 32 views
0

我剛剛學習c#並出現問題。我可以獲得幾乎所有的數據。但是,我怎樣才能得到這個XML的類別的數據?c# - 如何獲取子XML節點的數據

<data> 
 
<detail> 
 
    <product id="183438053251143" type_ID="1" > 
 
\t <title>Test</title> 
 
\t <description>Testdescription</description> 
 
\t <category id="111" level_sub="TestSub" level_top="TestTopLevel"/> 
 
    </product> 
 
    <product id="183438053252420" type_ID="1"> 
 
\t <title>Title2</title> 
 
\t <description>Testdescription</description> 
 
\t <category id="123" level_sub="TestSub2" level_top="TestTopLevel2"/> 
 
    </product> 
 
</detail> 
 
</data>

該代碼工作 - 但我發現,以獲得該類別的數據無解。

var products = from product in xml.Descendants("product") 
 
select product; 
 

 
      foreach (var item in products) 
 
      { 
 

 
\t  productid = item.Attribute("id").Value; 
 
       typeID = item.Attribute("type_ID").Value; 
 

 
       string myproduct = string.Format("/data/detail/product[@id={0}]", productid); 
 
       XmlNodeList productList = xmlnode.SelectNodes(myproduct); 
 

 
       foreach (XmlNode xnprogram in productList) 
 
       { 
 
        product_title = xnprogram["title"].InnerText.Trim(); 
 
        product_title = product_title.Replace("'", ""); 
 

 
        try 
 
        { 
 
         product_description = xnprogram["description"].InnerText.Trim(); 
 
        } 
 
        catch (Exception ex) 
 
        { 
 
         product_description = ""; 
 
        } 
 
\t \t } 
 
\t }

非常感謝。

+0

「數據」,在''是所有的屬性,所以你得到它,你得到其他屬性(例如,,'的productid = item.Attribute( 「ID」)值;')相同的方式。 – Tim

+0

。你試試這個嗎?後裔(「類別」)? – mybirthname

回答

1
var categoryElement=item.Element("category"); 
var idAttribute= categoryElement.Attribute("id"); 
var level_subAttribute=categoryElement.Attribute("level_sub"); 
.... 
+0

是的,var categoryElement = item.Element(「category」);完美的作品,我可以達到數據。太棒了,非常感謝你!而且如此快速,令人難以置信。 – Ralf