i have following XML-File
<?xml version="1.0" ?>
<server xmlns="exampleServer">
<system-properties>
<property name="prop0" value="null"/>
<property name="prop1" value="true"/>
<property name="prop2" value="false"/>
</system-properties>
</server>
and this.Code:
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("//system-properties/property");
But nodeList.Count are always 0. I have tried
root.SelectNodes("/system-properties/property");
root.SelectNodes("system-properties/property");
root.SelectNodes("//property");
..a.s.o. but nothing works. Evaluation of the var's show the Childnodes but there are not selected.
What did i wrong?
CodePudding user response:
The problem is that you have a namespace in your XML: <server xmlns="exampleServer">
. When using XPath, it's assumed that elements have no namespace if you don't add a prefix in your path. See the answer to a related question.
In your situation you need to use an XmlNamespaceManager with your XPath and specify the namespace of the elements you are searching for:
var nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("es", "exampleServer");
var properties = root.SelectNodes("//es:system-properties/es:property", nsMgr);
See this fiddle for a test run.