get attributes from xml tree using linq
Posted
by
nelsonwebs
on Stack Overflow
See other posts from Stack Overflow
or by nelsonwebs
Published on 2009-12-11T23:04:48Z
Indexed on
2011/01/07
10:53 UTC
Read the original article
Hit count: 196
linq-to-xml
I'm working with an xml file that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<element1 xmlns="http://namespace1/">
<element2>
<element3>
<element4 attr1="2009-11-09">
<element5 attr2="NAME1">
<element6 attr3="1">
<element7 attr4="1" attr5="5.5" attr6="3.4"/>
</element6>
</element5>
<element5 attr2="NAME2">
<element6 attr3="1">
<element7 attr4="3" attr5="4" attr6="4.5"/>
</element6>
</element5>
</element4>
</element3>
</element2>
</element1>
Where I need to loop through element5 and retrieve the attributes in an Ienumberable like this:
attr1, attr2, attr3, attr4, attr5, attr6
using linq to xml and c#. I can loop through the element5 and get all the attribute2 info using but I can't figure out how to get the parent or child attributes I need.
UPDATE: Thanks for the feeback thus far. For clarity, I need to do a loop through attribute5. So basically, what I have right now (which isn't much) is . . .
XElement xel = XElement.Load(xml);
IEnumberable<XElement> cList = from el in xel.Elements(env + "element2").Element
(n2 + "element3").Elements(n2 + "element4").Elements(ns + "element5") select el;
foreach (XElement e in cList)
Console.WriteLine(e.Attribute("attr2").Value.ToString());
This will give me the value all the attr 2 in the loop but I could be going about this all wrong for what I'm trying to acheive. I also need to collect the other attributes mentioned above in a collection (the Console reference is just me playing with this right now but the end result I need is a collection). So the end results would be a collection like
attr1, attr2, attr3, attr4, attr5, attr6
2009-11-09, name1, 1, 1, 5.5, 3.4
2009-11-09, name2, 1, 3, 4, 4.5
Make Sense?
© Stack Overflow or respective owner