gpt4 book ai didi

C# XPathSelectElement 和 xml with attribute xmlns ="http://www.w3.org/2000/09/xmldsig#"Help

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

我需要读取一个具有属性 xmlns="http://www.w3.org/2000/09/xmldsig#"的 xml 元素。XPathSelectElement 给出错误“对象引用未设置到对象的实例。”

这是示例代码。

var xml = "<root><tagA>Tag A</tagA><tagB>Tag B</tagB></root>";
XDocument xd = XDocument.Parse(xml);
var str = xd.XPathSelectElement("/root/tagB").ToString(SaveOptions.DisableFormatting);
Console.WriteLine(str);

上面代码的结果是:

<tagB>Tag B</tagB>

如果我输入属性,

var xml = "<root><tagA>Tag A</tagA><tagB xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Tag B</tagB></root>";

我遇到了错误。

Object reference not set to an instance of an object.

我是不是漏掉了什么?谁能帮帮我。 (我知道我可以通过使用其他方法获得。我只想知道我在这里缺少什么)

非常感谢。

最佳答案

您可以在 XmlNamespaceManager 中注册元素的命名空间:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("ns", "http://www.w3.org/2000/09/xmldsig#");

var str = xd.XPathSelectElement("/root/ns:tagB", nsmgr)
.ToString(SaveOptions.DisableFormatting);
Console.WriteLine(str);

关于C# XPathSelectElement 和 xml with attribute xmlns ="http://www.w3.org/2000/09/xmldsig#"Help,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6704093/

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