我需要一些帮助来检查节点是否存在。
我可以像这样选择节点
node["sa:name1"]["sa:name2"]["sa:name3"]
这个可以正常工作但是如果节点不存在我就会得到一个错误,我已经尝试过这个
if(node.SelectSingleNode("/sa:name1/sa:name2/sa:name3") != null)
但是这个没有帮助这只会产生一个新的错误
类型为'System.Xml.XPath '的异常。xpathexcexception '在System.Xml.dll中发生,但未在用户代码中处理
附加信息:需要命名空间管理器或XsltContext。该查询具有前缀、变量或用户定义函数。
使用http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.addnamespace.aspx
XmlNamespaceManager nsMgr = new XmlNamespaceManager(node.OwnerDocument.NameTable);
nsMgr.AddNamespace("sa", "http://example.com/");
XmlNode selected = node.SelectSingleNode("/sa:name1/sa:name2/sa:name3", nsMgr);
if (selected != null)
{
...
}
您当然需要使用输入文档中节点的URI而不是http://example.com/
,我认为名称空间URI是http://rep.oio.dk/uvm.dk/studieadm/common/xml/schemas/2006/02/20/
。
错误很明显:您需要在代码中添加名称空间管理器以使xpath查询工作。使用重载版本的SelectSingleNode(),它接受XmlNamespaceManager的一个实例作为参数。
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
//Create an XmlNamespaceManager for resolving namespaces.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:samples");
//Select the book node with the matching attribute value.
XmlNode book;
XmlElement root = doc.DocumentElement;
book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr);
Console.WriteLine(book.OuterXml);
http://msdn.microsoft.com/en-us/library/h0hw012b (v = vs.110) . aspx
您需要在调用SelectSingleNode
之前为文档添加一个命名空间管理器:
XmlNamespaceManager xmlnsMan = new XmlNamespaceManager(xml.NameTable);
xmlnsMan.AddNamespace("sa", "[namespace]);