【问题标题】:XPath issue with SelectSingleNode?SelectSingleNode 的 XPath 问题?
【发布时间】:2013-05-31 20:38:14
【问题描述】:

我正在尝试使用 SelectSingleNode 从 C# 中的 XML 字符串中获取节点。 XML 字符串来自外部来源。

string logonXML = @"<attrs xmlns=""http://www.sap.com/rws/bip\"">
                        <attr name=""userName"" type=""string""></attr>
                        <attr name=""password"" type=""string""></attr>
                        <attr name=""auth"" type=""string"" possibilities=""secEnterprise,secLDAP,secWinAD,secSAPR3"">secEnterprise</attr>
                    </attrs>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(logonXML);
XmlNode root = doc.DocumentElement;

XmlNode usernameXML = root.SelectSingleNode("//attr[@name='userName']");
Debug.WriteLine(usernameXML.OuterXml);

但是 usernameXML 是 null。我已经尝试将docroot 与XPath 查询的几个变体一起使用,但似乎找不到节点。这个 XPath 有什么问题?还是我用错了库?

【问题讨论】:

  • ("/attrs/attr[@name='username']) ?
  • ("/attrs/attr[1]") ?
  • 我试过这个,但仍然以null返回。
  • @RezaShirazian 也可以。仅当 XML 保持该顺序时。
  • 问题是元素有一个命名空间(默认来自父级)。 Stack Overflow 上有很多其他的例子——我个人会使用 LINQ to XML 代替(它有很好的命名空间支持),但也有 XPath 的替代品。

标签: c# xml xpath


【解决方案1】:

您需要考虑根节点上定义的 XML 命名空间

试试这样的:

string logonXML = @"<attrs xmlns=""http://www.sap.com/rws/bip"">
                        <attr name=""userName"" type=""string""></attr>
                        <attr name=""password"" type=""string""></attr>
                        <attr name=""auth"" type=""string"" possibilities=""secEnterprise,secLDAP,secWinAD,secSAPR3"">secEnterprise</attr>
                    </attrs>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(logonXML);

// define the XML namespace(s) that's in play here
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "http://www.sap.com/rws/bip");

// select including the XML namespace manager
XmlNode usernameXML = doc.SelectSingleNode("/ns:attrs/ns:attr[@name='userName']", nsmgr);

string test = usernameXML.InnerText;

【讨论】:

  • 谢谢,这就是问题所在。 doc.DocumentElement.NamespaceURI 也会给我命名空间,所以我不必硬编码。
  • @Paul:XML 命名空间的存在是有原因的——你不应该试图避免和剥离它们——了解它们,习惯它们,尊重它们!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
相关资源
最近更新 更多