如何在C#中向XPath添加名称空间?
我试图解析一个XML文件:但我得到了一个错误 需要命名空间管理器或XlstContext。此查询具有前缀、变量或用户定义函数。“ 代码: 我发现这个错误是由于缺少名称空间造成的,所以我尝试这样添加它:如何在C#中向XPath添加名称空间?,c#,xml,xpath,namespaces,C#,Xml,Xpath,Namespaces,我试图解析一个XML文件:但我得到了一个错误 需要命名空间管理器或XlstContext。此查询具有前缀、变量或用户定义函数。“ 代码: 我发现这个错误是由于缺少名称空间造成的,所以我尝试这样添加它: XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable); nameSpace.AddNamespace("ir",path); 现在我有一个新错误:“System.NullRef
XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);
nameSpace.AddNamespace("ir",path);
现在我有一个新错误:“System.NullReferenceException:对象引用未设置为对象的实例。”第行:
我的代码出了什么问题?名称空间处理总是让我感到困惑,所以我不得不花点时间来解决这个问题。最大的问题是,当添加名称空间时,您提供了该名称空间的地址,而不是重用xml文档本身的路径
XPathDocument oXPathDocument = new XPathDocument(path);
XPathNavigator oXPathNameNavigator = oXPathDocument.CreateNavigator();
XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);
//use the namespace address provided in the XML, not the path to the xml itself
nameSpace.AddNamespace("ir","http://www.ikea.com/v1.0");
//now you have to scope your query to the namespace you just defined, otherwise xpath will assume the node is not in a namespace
productModel.productName = oXPathNameNavigator.SelectSingleNode("//ir:ikea-rest/products/product/name", nameSpace).Value;
我在LinqPAD中对此进行了测试,并且我能够正确地找到您感兴趣的节点。也许:oXPathNameNavigator。选择SingleNode(“名称”)。值等于null?是的,它为null,但我不知道为什么。在xml标记中,“name”的值为“ABORG”,那么我如何更改代码以获得该值?
productModel.productName = oXPathNameNavigator.SelectSingleNode("name").Value;
XPathDocument oXPathDocument = new XPathDocument(path);
XPathNavigator oXPathNameNavigator = oXPathDocument.CreateNavigator();
XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);
//use the namespace address provided in the XML, not the path to the xml itself
nameSpace.AddNamespace("ir","http://www.ikea.com/v1.0");
//now you have to scope your query to the namespace you just defined, otherwise xpath will assume the node is not in a namespace
productModel.productName = oXPathNameNavigator.SelectSingleNode("//ir:ikea-rest/products/product/name", nameSpace).Value;