I need some help with LINQ and XML. I’ve read numerous articles but just can’t seem to find what I’m looking for as most people are looping through results to get values. I have the following XML and I need to access a specific element based first on the section name and then on the control id.
<formData>
<section name="SectionA">
<control id="Textbox1" type="TextBox">
<value>Value1</value>
</control>
<control id="Textbox2" type="TextBox">
<value>Value2</value>
</control>
<control id="Textbox3" type="TextBox">
<value>Value2</value>
</control>
</section>
<section name="SectionB" />
<section name="SectionC" />
<section name="SectionD" />
<section name="SectionE" />
</formData>
I’m using the following code to get the element I need.
IEnumerable<XElement> fields = xDocument.Element("formData").Elements("section")
.Where(m => m.Attribute("name").Value == "SectionA")
.Single()
.Elements("control")
.Where(f => f.Attribute("id").Value == "Control1");
Which results in the following element:
<control id="Textbox1" type="TextBox">
<value>Value1</value>
</control>
However, that’s as far as I can get… I need three separate values, the ID, the TYPE and the Value. How do I go about this without using foreach or nested foreach loops?
Thank you
If you would be ok using anonymous types, you could do this: