Florin M.
Florin M.

Reputation: 2169

get child nodes xml attribute value

<test>
    <acc id="1"> acc1 </acc>
    <acc id="2"> acc2 </acc>
    <acc id="3"> acc3 </acc>
    <acc id="4"> acc4 </acc>
</test>

For example, if I want to take the value of each <acc> element:

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);
}

But how to substract all the attribute "id" values of each <acc> elements?

Upvotes: 0

Views: 2138

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

You can easily get this using LINQ-to-XML:-

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

Or if you prefer query syntax then:-

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

Upvotes: 3

Related Questions