Is there any way to use a LINQ to XML to query an XML document like the one below to create new (anonymous or strongly typed) objects from the child elements of a descendant?
Here is my XML document:
<Root>
<Rules>
<Rule Name="Rule_A">
<Parameter>
<Name>Parameter 1</Parameter>
<Value>100</Value>
</Parameter>
<Parameter>
<Name>Parameter 2</Parameter>
<Value>200</Value>
<Parameter>
</Rule>
<Rule Name="Rule_B">
<Parameter>
<Name>Parameter 1</Parameter>
<Value>600</Value>
</Parameter>
<Parameter>
<Name>Parameter 2</Parameter>
<Value>300</Value>
<Parameter>
</Rule>
</Rules>
</Root>
My LINQ query looks like this:
Dim RuleName as String = "Rule_A"
Dim parms() = (From p In pXDoc.Descendants("Rule") _
Where p.Attributes("Name").Any And p.Attribute("Name").Value.Equals(RuleName) _
Select New DataParameter With { _
'' Here is where I would like to pull the values of the Parameter
'' elements underneath "Rule_A" and construct an object like below
.Name = LINQ magic to get the value of <Name>
.Value = LINQ magic to get the value of <Value>
}).ToArray
After running that query, my Parms() array would have two objects in it representing the Name/Values of "Parameter 1" and "Parameter 2" that fall under "Rule_A".
The closest I have been able to get is using the p.Element(Parameter).Element(Name).Value, but that won’t work as I will only get the first Parameter element. I also tried using Elements(), but was not able to figure out how I would get the value of each.
You can do it like this: