Josh
Josh

Reputation: 1610

Linq to XML, extracting attributes and elements

I am new to XML and Linq to XML and I just can't find a good guide that explains how to work with it. I have a simple XML string structured as follows

<mainitem>

  <items>
    <itemdescription>ABC</itemdescription>
    <item>
      <itemtext>XXX</itemtext>
    </item>
    <item>
      <itemtext>YYY</itemtext>
    </item>
    <item>
      <itemtext>ZZZ</itemtext>
    </item>
  </items>

  <overalldescription>ABCDEFG</overalldescription>
  <itemnodes>
    <node caption="XXX" image="XXX"></node>
    <node caption="YYY" image="YYY"></node>
    <node caption="ZZZ" image="ZZZ"></node>
  </itemnodes>
</mainitem>

I am using C# code like

 var Items = (from xElem in XMLCODEABOVE.Descendants("item")
              select new ItemObject
              {
                  ItemObjectStringProperty = xElem.Element("itemtext").Value,
              }
              );

to extract a list of the itemtext objects for use with my code. Where I need help is in extracting a list of the caption and image attributes of my node elements. I also need the overalldescription and the itemdescription. I have tried every variation of the above code substituting Descendant for Elements, Element for Attribute etc. I know this is probably a basic question but there doesn't seem to be a straight forward guide out there to explain this to a beginner.

Upvotes: 1

Views: 4879

Answers (1)

John Sheehan
John Sheehan

Reputation: 78104

To get the captions

// IEnumerable<string>
var captions = from node in doc.Descendants("node")
               select node.Attribute("caption").Value;

Or both the captions and image attributes in one shot:

// IEnumerable of the anonymous type
var captions = from node in doc.Descendants("node")
               select new { 
                   caption = node.Attribute("caption").Value,
                   image = node.Attribute("image").Value
               };

For the descriptions:

 // null ref risk if element doesn't exist
 var itemDesc = doc.Descendants("itemdescription").FirstOrDefault().Value;
 var overallDesc = doc.Descendants("overalldescription ").FirstOrDefault().Value;

Upvotes: 3

Related Questions