XmlDocument.SelectSingleNode returns null for root node
-
19-09-2019 - |
Question
I have several xml files whose postfix is not .xml, but .component Now I want to handle them in the c# program, but It seems that the c# cant even find the root element of these xml files
var doc = new XmlDocument();
doc.Load(path); // MG: edited to Load based on comment
XmlNode root = doc.SelectSingleNode("rootNodename");
It seems that the root is null, How should I cope with this?
Solution
Given that you've resolved the Load
/LoadXml
confusion, I expect the issue is namespaces; do you have example xml? Handling xml with namespaces gets... "fun" ;-p
For example:
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<test xmlns='myFunkyUri' value='abc'/>");
// wrong; no namespace consideration
XmlElement root = (XmlElement)doc.SelectSingleNode("test");
Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value"));
// right
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("x", "myFunkyUri"); // x is my alias for myFunkyUri
root = (XmlElement)doc.SelectSingleNode("x:test", nsmgr);
Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value"));
Note that even if your xml declares xml aliases, you may still need to re-declare them for your namespace-manager.
OTHER TIPS
LoadXml takes an XML string, not a file path. Try Load instead. Load doesn't care about the file extension.
Here is a link to the documention for Load: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx
I was having this problem try this: Putting a dash in front of rootNodename Instead of this: XmlNode root = doc.SelectSingleNode("rootNodename");
Do this: XmlNode root = doc.SelectSingleNode("/rootNodename");