2016-12-06 8 views
0

Ich bin gerade beim Lernen C# und habe ein Problem. Ich kann fast alle Daten bekommen. Aber wie bekomme ich die Daten der Kategorie dieses XML?C# - Wie bekomme ich die Daten von Sub-XML-Knoten

<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>

Dieser Code funktioniert - aber ich fand die Kategoriedaten zu erhalten keine Lösung um.

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 }

Vielen Dank.

+0

Die "Daten" in '' sind alle Attribute, so dass Sie es auf die gleiche Weise weitere Attribute erhalten erhalten (zum Beispiel ,, 'productid = item.Attribute ("id") Wert,.'). – Tim

+0

.Descendants ("Kategorie") versuchst du das? – mybirthname

Antwort

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

Ja, var categoryElement = item.Element ("category"); funktioniert perfekt und ich kann die Daten erreichen. So großartig, vielen Dank! Und so schnell, unglaublich. – Ralf

Verwandte Themen