Question

In C#, how can I select values from an XML file using LINQ?

Here is my XML file:

<?xml version="1.0" encoding="utf-8"?>
<Level1>
<Level2>
    <Value1>This-is-value-1</Value1>
    <Value2>This-is-value-2</Value2>
    <Value3>This-is-value-3</Value3>
    <Value4>This-is-value-4</Value4>
</Level2>  
</Level1>

Here is the code I have so far:

var doc = XDocument.Load(filename);
var values = from lv1 in doc.Descendants("level1")
            from lvl2 in lv1.Descendants("Level2")
            select new {
                Value1 = lv1.Attribute("Value1").Value,
                Value2 = lv1.Descendants("Value2").Value,
                Value3 = lv1.Descendants("Value3").Value,
                Value4 = lv1.Descendants("Value4").Value,
            };

I am wanting to retrieve the following values:

  • Value1
  • Value2
  • Value3
  • Value4

May I please have some help to get this working?

EDIT

Sorry, I meant to add that I would like to place the values in local fields.

E.g. Here are the field names:

string Value1;
string Value2;
string Value3;
string Value4;

May I have some help to place the values from the LINQ statement into the local fields?

Was it helpful?

Solution

There are various things wrong with your current code:

  • You're using Attribute when there aren't attributes in the XML
  • You're trying to use the Value property on Descendants, but Descendants returns IEnumerable<XElement>
  • You're not using lv2 anywhere
  • You're looking for level1 as an element name rather than Level1. (XML is case-sensitive.)

I suspect you just want:

var doc = XDocument.Load(filename);
var values = from level in doc.Descendants("Level1").Descendants("Level2")
             select new {
                 Value1 = (string) level.Element("Value1"),
                 Value2 = (string) level.Element("Value2"),
                 Value3 = (string) level.Element("Value3"),
                 Value4 = (string) level.Element("Value4")
             };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top