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
See more on this question at Stackoverflow