XPath issue with SelectSingleNode?

本文关键字:SelectSingleNode with issue XPath | 更新日期: 2023-09-27 18:16:32

我试图在c#中使用SelectSingleNode从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有什么问题?还是我用错图书馆了?

XPath issue with SelectSingleNode?

您需要考虑在根节点上定义的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;
相关文章:
  • 没有找到相关文章