Paul
Paul

Reputation: 3954

XPath issue with SelectSingleNode?

I'm trying to get a node from an XML string in C# using SelectSingleNode. The XML string comes from an external source.

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);

However usernameXML is null. I've tried using both the doc and root with a couple variations of XPath queries, but can't seem to find the node. What is wrong with this XPath? Or am I using the library wrong?

Upvotes: 1

Views: 400

Answers (1)

marc_s
marc_s

Reputation: 754220

You need to take into account the XML namespace that's defined on your root node!

Try something like this:

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;

Upvotes: 2

Related Questions