简体   繁体   中英

Accessing the element type in XML using LINQ to XML

As seen in the code snippet below, the name given to each of my elements in the XML file vary. Element 1 is of type testcheck1 and Element 2 is of type testcheck2.

<?xml version="1.0" encoding="utf-16"?>

<Tests xmlns="urn:lst-emp:emp">

  <testcheck1 xmlns="">
    <Type>string</Type>
    <Value>value1</Value>
  </testcheck1>

  <testcheck2 xmlns="">
    <Type>int</Type>
    <Value>1232</Value>
  </testcheck2>

</Tests>

I can use this code:

XElement xelement = XElement.Load("project_data.xml");
IEnumerable<XElement> employees = xelement.Elements();
Console.WriteLine("List of all Values:");
foreach (var employee in employees)
{
    StreamWriter file2 = new StreamWriter("C:\\tempFolder\\results.xml", true);
    file2.WriteLine(employee.Element("Value").Value);
    file2.Close();
}

to get each of the values in the XML file. (like value1 and 1232 ).

I was wondering if it were possible to get the element types that I have defined in the XML (like testcheck1 and testcheck2 ) using LINQ to XML.

It sounds like you're really just looking for the element name, possibly its LocalName :

var root = XElement.Load("project_data.xml");
foreach (var element in root.Elements())
{
    Console.WriteLine("{0}: {1}", 
                      element.Name.LocalName,
                      element.Element("Value").Value);
}

(Talking about the "type" of an element when you also have a Type child element is a bit confusing, mind you...)

That will print out:

testcheck1: value1
testcheck2: 1232

You can get Type element same way as Value element:

foreach (var employee in employees)
{
    StreamWriter file2 = new StreamWriter("C:\\tempFolder\\results.xml", true);
    var value = (string)employee.Element("Value");
    var type = (string)employee.Element("Type");
    var name = e.Name.LocalName;
    // ...
}

You also can create list of anonymous 'employee' objects with value and type:

var employees = from e in xelement.Elements()
                select new {
                   Name = e.Name.LocalName,
                   Type = (string)e.Element("Type"),
                   Value = (string)e.Element("Value")
                };

foreach (var employee in employees)
{
    // use employee.Name, employee.Type and employee.Value
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM