Linq to XML: Returning attributes from Children of the same name and Parents of the same name
So, the noobie question of the day...
I have an XML file with the following structure:
<result>
<rowSet name="name">
<row name="name1" />
<row name="name2" />
<row name="name3" />
</rowSet>
<rowSet name="type">
<row type="type1" />
<row type="type2" />
<row type="type3" />
</rowSet>
etc..
</result>
I've been trying, and rather unsuccessfully, to get the row attributes from a single rowSet based off the rowSet:attribute name. In other words, I'm trying to pull the attributes from the "row"s which are only contained under a rowSet:Attribute of a specific name.
I've tried using:
var rowSet = from rs in xmlDoc.Descendants("result")
where rs.Descendants("rowset").Attributes("name").Any(a => a.Value == "name")
select new
{
row = from r in xmlDoc.Descendants("row")
select new
{
skillID = r.Attribute("name"),
}
};
However, this doesn't give more than a single result. Been rather frustrating, and yet again...after trying 15 different suggestions I have been unable to remember the original code for the reader.
An answer was given:
var rowNames = (from i in xmlDoc.Descendants("rowSet")
where (string)i.Attribute("name") == "name"
select i.Descendants("row")) // Had to move this last ) to...
.Select(r => (string)r.Attribute("name")); // Here in o开发者_高级运维rder to get it to work
I believe this worked but I'm too noobish to find out how to iterate through it, even though I can get to the data through the "Result View" of the debugger when the program is running.
Ok, so I'm able to get that query to run right (by moving a ")" first) and when I start stepping through the code, the rowNames has values in it. However, I've been very unsuccessful in displaying the information in any way. I'm playing with this in a console app, fyi.
So that's the first problem.
The second is, if I start making my XML a bit more complicated, by adding multiple attributes to the row elements, like:
<result>
<rowSet name="name">
<row fName="Ted" lName = "Happy" />
<row name="Billy" lName = "Maddison"/>
<row name="John" lName = "Doe"/>
</rowSet>
<rowSet name="type">
<row type="type1" type2 ="Hero"/>
<row type="type2" type2 ="Villain" />
<row type="type3" type2 ="Neutral"/>
</rowSet>
</result>
How then do I retrieve all attributes in an element?
This seems so basic, which is why I'm feeling quite retarded at the moment.
You can get the names alone easily enough:
var rowNames = from i in xmlDoc.Descendants("rowSet")
where (string)i.Attribute("name") == "name"
from r in i.Descendants("row")
select (string)r.Attribute("name");
Just adjust the strings to get the other. (You might throw this in a method and use parameters, for example.)
This is a bit guesswork, but do you mean:
from rs in xmlDoc.Descendants("result").Descendants("rowSet")
where (string)rs.Attribute("name") == "name"
from r in rs.Descendants("row")
select new { skillID = (string)r.Attribute("type") }
精彩评论