xmldocument.SelectSingLenode返回root节点的null
-
19-09-2019 - |
题
我有几个XML文件的后缀不是.xml,但是.component现在我想在C#程序中处理它们,但是C#甚至找不到这些XML文件的根元素
var doc = new XmlDocument();
doc.Load(path); // MG: edited to Load based on comment
XmlNode root = doc.SelectSingleNode("rootNodename");
看来根是无效的,我应该如何应对?
解决方案
考虑到您已经解决了 Load
/LoadXml
混乱,我希望这个问题是名称空间。您有示例XML吗?使用名称空间处理XML ...“娱乐”; -P
例如:
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"));
请注意,即使您的XML声明了XML别名,您仍然需要重新调整它们的命名空间管理器。
其他提示
LOADXML采用XML字符串,而不是文件路径。尝试加载。负载不在乎文件扩展名。
这是指向负载文档的链接:http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx
我遇到了这个问题,请尝试以下方法:将破折号放在rootnodeName的前面,而不是:xmlnode root = doc.SelectSingLenode(“ rootnodeName”);
这样做:xmlnode root = doc.SelectSingLenode(“/rootnodeName”);
不隶属于 StackOverflow