LINQ to XML New Question: Returned Nodes Node Name
Hello!
If I have XML like:
<Root>
<AlphaSection>
.
.
.
</AlphaSection>
<BetaSection>
<Choices>
<SetA>
<Choice id="choice1">Choice One</Choice>
<Choice id="choice2">Choice Two</Choice>
</SetA>
<SetB>
<Choice id="choice3">Choice Three</Choice>
<Choice id="choice4">Choice Four</Choice>
</SetB>
</Choices>
</BetaSection>
<GammaSection>
.
.
.
</GammaSection>
</Root>
I would like to get all the Choice items in the "BetaSection", no matter which one they are set to. I've tried the following:
var choiceList = from choices in myXDoc.Root.Element("BetaSection").Elements("Choices")
where (choices.Name == "Choice")
select new
{
Name = choices.Attribute("id").Value,
Data = choice.Value
};
But to no avail. How can i do this?
Thank.
0
source to share
2 answers
You don't need a where clause at all - you just need to change the call to Elements for descendants:
var choiceList = myXDoc.Root
.Element("BetaSection")
.Descendants("Choice")
.Select(element => new
{
Name = element.Attribute("id").Value,
Data = element.Value;
});
(I converted it from a query expression to simple dot notation as I don't think the query expression really helped you.)
+6
source to share
I would write this instead. I prefer SQL syntax over method syntax, but that's a matter of taste ...
class Program
{
static void Main(string[] args)
{
String xml = @"<Root>
<AlphaSection></AlphaSection>
<BetaSection>
<Choices>
<SetA>
<Choice id='choice1'>Choice One</Choice>
<Choice id='choice2'>Choice Two</Choice>
</SetA>
<SetB>
<Choice id='choice3'>Choice Three</Choice>
<Choice id='choice4'>Choice Four</Choice>
</SetB>
</Choices>
</BetaSection>
<GammaSection></GammaSection>
</Root>";
XElement xmlElement = XElement.Parse(xml);
var choiceList = from c in xmlElement.Descendants().Elements("Choice")
select new {
Name = c.Attribute("id").Value,
Data = c.Value
};
foreach (var choice in choiceList) {
Console.WriteLine("Name: {0} Data: {1}", choice.Name, choice.Data );
}
}
}
0
source to share