2017-01-13 3 views
0
<test> 
    <acc id="1"> acc1 </acc> 
    <acc id="2"> acc2 </acc> 
    <acc id="3"> acc3 </acc> 
    <acc id="4"> acc4 </acc> 
</test> 

Zum Beispiel, wenn ich den Wert jedes <acc> Element nehmen wollen:erhalten Kindknoten xml Attributwert

var iAccs = xdoc.Descendants("test").Elements("acc").Select(p => p.Value); 
List<string> myList = new List<string>(); 
foreach(string p in iAccs) 
{ 
    myList.Add(p); 
} 

Aber wie alle das Attribut „id“ Werte jedes <acc> Elemente subtrahieren?

+1

Meinen Sie "extract"? –

+0

Um beide in einer Abfrage zu erhalten: var iAccs = xdoc.Descendants ("test"). Elemente ("acc"). Wählen (p => new { value = (string) p, id = (int) p. Attribut ("id") }). ToList(); – jdweng

Antwort

3

Sie können leicht zu bekommen, dies mit LINQ-to-XML: -

XDocument xdoc = XDocument.Load(@"You XML file path"); 
List<string> result = xdoc.Descendants("acc") 
          .Select(x => (string)x.Attribute("id")).ToList(); 

Oder wenn Sie Abfragesyntax bevorzugen dann: -

List<int> result2 = (from x in xdoc.Descendants("acc") 
        select (int)x.Attribute("id")).ToList(); 
+1

Es funktioniert. Danke für Ihre Hilfe! –