Search code examples
c#asp.netsqlsqlxml

How to use Linq to parse through XML easly - Need some sample code


I am using XML Auto in my SQL Server to query data out. I want to know how best to parse through the data that it provides.

My end goal is to provide a list of items with their values, but I don't know how many columns or what the names of the columns will be until at least the data is pulled form SQL at runtime.

Here is a sample XML

  <animals>
    <animal name="Pig">
      <meat>
        <name>Prosciutto</name>
      </meat>
      <meat>
        <name>Speck</name>
      </meat>
    </animal>
    <animal name="Cow">
      <meat>
        <name>Clod</name>
      </meat>
      <meat>
        <name>Brisket</name>
      </meat>
      <meat>
        <name>Tri-tip</name>
      </meat>
    </animal>
    <animal name="Chicken">
      <meat>
        <name>Drumstick</name>
      </meat>
    </animal>
  </animals>

How can I show this in a list, and perform Linq2SQL (or Linq2XML)?


Solution

  • To select a list

    var q = from x in doc.Descendants()
            select x.Value;
    

    to select specific nodes, e.g. animals, do doc.Descendants("animal")

    to select specific value, e.g. name of an animal do select x.Attribute("name").Value

    Demo: https://dotnetfiddle.net/TdCWjE