Florin M. Florin M. - 7 days ago 6
C# Question

get all child nodes value using foreach

<R>
<tests>
<test language="en"> hello </test>
<test language="it"> ciao </test>
<test language="hu"> szia </test>
<test language="es"> ola </test>
</tests>
</R>


The above part of XML is contained in a (XML) file. I do want foreach test xml element to read and get the XML value.

I tried something like this:

XDocument xdoc = XDocument.Load(theXmlURLpath);

foreach (var iDescription in xdoc.XPathSelectElements("R/tests"))
{
string lang = iDescription.Attribute("language").Value; // en / it / hu / es
string text= iDescription.Value; // hello or ciao ...
switch(iLang)
{
case "en":
// do something
break;
case "it":
// do something
break;
case "hu":
// do something
break;
case "es":
// do something
break;
}
}

Answer

Your XPath does not select the <test/> elements, but the <tests/> parent element.

Try

xdoc.XPathSelectElements("R/tests/test")