Jac*_*cob 3 c# xml linq xpath xml-namespaces
我需要读取一个属性为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);
Run Code Online (Sandbox Code Playgroud)
上面代码的结果是:
<tagB>Tag B</tagB>
Run Code Online (Sandbox Code Playgroud)
如果我把属性,
var xml = "<root><tagA>Tag A</tagA><tagB xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Tag B</tagB></root>";
Run Code Online (Sandbox Code Playgroud)
我收到了错误.
Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?任何人都可以帮助我.(我知道我可以通过其他方法获得.我只是想知道我在这里缺少什么)
非常感谢你.
您可以在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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3360 次 |
最近记录: |