AvacadoRancher
AvacadoRancher

Reputation: 135

LINQ Parsing XML

Give this xml structure:

    <store-fax-info>
      <store-info store-status="1" store-service-type="2">
        <store-guid>blah-blah-blah-blah</store-guid>
        <store-name>Avacados R Us</store-name>
        <phone>555-555-5555</phone>
        <fax>123-456-789</fax>
        <attention>Rockhead Rumble</attention>
      </store-info>
      <selected-clerk>
        <clerk-info guid="x">
          <clerk name="full-name" label="Clerk Name" value="" />
        </clerk-info>
        <item-info>
          <item-name="item-model" label="Item Model" value="Super Spuds" />
          <item-name="item-model-num" label="Model Number value="55555" />
          <item-name="family" label="Veggie Family" value="Tuber" />
          <item-name="serial-number" label="Serial Number" value="ABC123456A" />
          <item-name="date-checked" label="Last Date Checked" value="Mar 15 2012 11:00AM" />
          <item-name="item-weight" label="Weight" value="20lbs />
        <item-info>
      </selected-clerk>
    </store-fax-info>

I'm after the attributes in the item-info node, specifically the last value of each attribute. The kicker is, I only need 4 of the 6 attributes. I've been hammering on this all day. I take that xml and shove it in an XElement, let's call it info. When I write this:

    var query = from i in info.Elements("item-info")
                from j in i.Elements()
                select j;

At this point I can see all six of the item-name... lines. The purpose is I would like to get the values and put them into a class object. Roughly pseudocoded the desired outcome is....

    select new MyObject()
    {
        Product = query.SuperSpuds,
        Number = query.55555,
        SerialNumber = query.ABC123456A,
        CheckedDate = query.Mar 15 2012 11:00AM,
    }

I can't seem to massage the LINQ query to do what I need.

Upvotes: 1

Views: 179

Answers (1)

the_joric
the_joric

Reputation: 12226

First of all, your xml is not well-formed.

Things like

<item-name="item-model" label="Item Model" value="Super Spuds" />

are not allowed. If you want to store text inside element use this:

<item-name label="Item Model" value="Super Spuds">item-model</item-name>

However if you change XML to valid one the following code may help you:

var xElements = xElement.Descendants("item-name").Attributes("value").ToList();

var o = new MyObject()
            {
                Product = xElements[0].Value,
                Number = xElements[1].Value,
                SerialNumber = xElements[2].Value,
                CheckedDate = xElements[3].Value
            };

Upvotes: 1

Related Questions