[英]C# XPathSelectElement and xml with attribute xmlns=“http://www.w3.org/2000/09/xmldsig#” Help
I need to read an xml element which has attribute xmlns="http://www.w3.org/2000/09/xmldsig#".我需要阅读具有属性 xmlns="http://www.w3.org/2000/09/xmldsig#" 的 xml 元素。 XPathSelectElement is giving error "Object reference not set to an instance of an object." XPathSelectElement 给出错误“对象引用未设置为 object 的实例。”
Here is the sample code.这是示例代码。
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);
The result of the above code is:上面代码的结果是:
<tagB>Tag B</tagB>
If I put attribute,如果我把属性,
var xml = "<root><tagA>Tag A</tagA><tagB xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Tag B</tagB></root>";
I got error.我有错误。
Object reference not set to an instance of an object.
Am I missing something here?我在这里错过了什么吗? Can anyone please help me out.谁能帮帮我。 (I know I can get by using other methods. I just want to know what I am missing here) (我知道我可以通过其他方法得到。我只想知道我在这里缺少什么)
Thank you very much.非常感谢。
You can register the element's namespace in an XmlNamespaceManager :您可以在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);
You should read some about XML.您应该阅读一些关于 XML 的信息。 The tagB
in the second example is in a different namespace.第二个示例中的tagB
位于不同的命名空间中。 By default, you're querying the empty namespace, if you want to query a different one you need to use a namespace manager and assign the namespace to a prefix, then prefix the element name with this same prefix and it will work again.默认情况下,您查询的是空命名空间,如果要查询不同的命名空间,您需要使用命名空间管理器并将命名空间分配给前缀,然后使用相同的前缀作为元素名称的前缀,它将再次起作用。
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xd.CreateNavigator().NameTable);
nsmgr.AddNamespace("xmldsig", "http://www.w3.org/2000/09/xmldsig#");
var str = xd.XPathSelectElement("/root/xmldsig:tagB", nsmgr).ToString(SaveOptions.DisableFormatting);
It's not just any attribute.这不仅仅是任何属性。 For example try with例如尝试
var xml = "<root><tagA>Tag A</tagA><tagB attr=\"http://www.w3.org/2000/09/xmldsig#\">Tag B</tagB></root>";
to see that it works.看看它是否有效。
The problem is that you change the namespace by using xmlns, so your XPath doesn't match anymore.问题是您使用 xmlns 更改了命名空间,因此您的 XPath 不再匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.