gpt4 book ai didi

c# - XmlDocument.SelectSingleNode 为根节点返回 null

转载 作者:数据小太阳 更新时间:2023-10-29 02:49:33 29 4
gpt4 key购买 nike

我有几个 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");

root好像是null,我应该怎么处理?

最佳答案

鉴于您已经解决了 Load/LoadXml 混淆问题,我认为问题出在命名空间上;你有示例 xml 吗?使用 namespace 处理 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 别名,您可能仍需要为您的命名空间管理器重新声明它们。

关于c# - XmlDocument.SelectSingleNode 为根节点返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1169536/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com