In XML Document:
Foo.xml
<products>
<product>
<id>1</id>
<name>Foo</name>
</product>
<product>
<id>2</id>
<name>Bar</name>
</product>
</products>
How to get this root element, iterate over his child elements and get their properties?
Bar.cs
XmlDocument doc = new XmlDocument();
doc.Load(path "/foo.xml");
XmlNode mainNode = doc.DocumentElement.SelectSingleNode("products");
XmlNode root = mainNode.FirstChild; //null
foreach (XmlNode node in mainNode)
{
int id = Convert.ToInt32(node["id"].InnerText);
string name = node["name"].InnerText);
list.Items.Add(id);
list.Items.Add(name);
}
This code implicates that mainNode is null. What is the best practise of doing that?
CodePudding user response:
The DocumentElement
is the outermost element of the XML, i.e. the <products>
element. You can't select another <products>
element below it.
What you can do:
XmlNode mainNode = doc.SelectSingleNode("products");
or
XmlNode mainNode = doc.DocumentElement;
or
XmlNode mainNode = doc.DocumentElement.SelectSingleNode("//products");
The second one is probably the fastest, since it does not need to parse and process a query. The last one is overkill and should be avoided for clean code reasons (KISS principle).