I have an XmlNodeList
that would like to find a special node inside it.
I used the following code but I it does not find the desired node spite of it is in the XmlNodeList
.
string ID = "9";
public void XMlNodeFind(XmlNodeList steps, string ID)
{
var resultNodes = new List<XmlNode>();
foreach (XmlNode node in steps)
{
if (node.Attributes["name"].Value.Equals(ID))
{
resultNodes.Add(node);
}
}
}
and here is XML file:
<?xml version="1.0" encoding="utf-8"?>
<files>
<file name="1">
<file name="3">
<file name="9">
</file>
</file>
</file>
<file name="2">
<text here are some text/>
</file>
</files>
As you've said you can use LINQ to XML, I'd use something like this:
public List<XElement> FindElementsByName(XDocument doc, string name)
{
return doc.Descendants()
.Where(x => (string) x.Attribute("name") == name)
.ToList();
}
(In C# 6 you could use an expression-bodied method, of course.)
See more on this question at Stackoverflow