C# Xmlnode如何查看节点是否存在
我需要一些帮助来检查节点是否存在 我可以像这样选择节点C# Xmlnode如何查看节点是否存在,c#,xml,xpath,xmlnode,C#,Xml,Xpath,Xmlnode,我需要一些帮助来检查节点是否存在 我可以像这样选择节点 node["sa:name1"]["sa:name2"]["sa:name3"] 这很好,但是如果节点不存在,我会出错,我已经试过了 if(node.SelectSingleNode("/sa:name1/sa:name2/sa:name3") != null) 但这并没有帮助,这只是犯了一个新的错误 System.Xml.dll中发生类型为“System.Xml.XPath.XPathException”的异常,但未在用户代码中处理
node["sa:name1"]["sa:name2"]["sa:name3"]
这很好,但是如果节点不存在,我会出错,我已经试过了
if(node.SelectSingleNode("/sa:name1/sa:name2/sa:name3") != null)
但这并没有帮助,这只是犯了一个新的错误
System.Xml.dll中发生类型为“System.Xml.XPath.XPathException”的异常,但未在用户代码中处理
其他信息:需要名称空间管理器或XsltContext。此查询具有前缀、变量或用户定义的函数。错误很明显:您需要在代码中添加命名空间管理器,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);
在调用
选择SingleNode
之前,您需要为文档添加名称空间管理器:
XmlNamespaceManager xmlnsMan = new XmlNamespaceManager(xml.NameTable);
xmlnsMan.AddNamespace("sa", "[namespace]);
使用
而不是
http://example.com/
您当然需要使用输入文档中节点的URI,我认为名称空间URI是http://rep.oio.dk/uvm.dk/studieadm/common/xml/schemas/2006/02/20/
你好,Martin,我很确定我必须使用此URI“”,但现在当我尝试选择SingleNode时,我总是得到null?请尝试http://rep.oio.dk/uvm.dk/studieadm/common/xml/schemas/2006/02/20/
,没有文件名。感谢您的帮助,但我刚刚尝试了此操作,此更改仍然为空。请编辑您的问题,并提供显示其中声明的名称空间的XML输入示例。找到此帖子,我需要在xpath前面“/”以从当前节点进行选择。但是谢谢你剩下的时间,这对我很有帮助。
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)
{
...
}