Reputation: 267
I have a simple xml, I created a XmlDocument out of it and used Xpath to fetch a node, I need to pass this node to other parts of the code where I may use further xpath functions on the XmlNode object to get other sub nodes. But in the code below
string xmlString = "<catalog><music><cds><cd><title>First Title</title><author>Author 1</author></cd><cd><title>Second Title</title><author>Author 2</author></cd></cds></music></catalog>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
XmlNode musicNode = xmlDocument.SelectSingleNode("/catalog/music");
XmlNode cdsNode = musicNode.SelectSingleNode("/cds");
when I print the name of the musicNode, I am getting "music", so I assume that I have the "music" node. So I again applied xpath expression "/cds" on the music node assuming I would get the "cds" XmlNode, but cdsNode in the code returns undefined value, but if I do
XmlNode cdsNode = musicNode.SelectSingleNode("/catalog/music");
I am getting a valid value for cdsNode that is the "music" node again, I suppose musicNode represents the XmlDocument instead of the "music" XmlNode??? Am I missing something, I am from Java and in Java navigating to subnodes from Node is possible using xpath, like an xpath expression "/cds" on the musicNode would have returned a valid cdNode
Upvotes: 2
Views: 1223
Reputation: 107367
/ will always go back to the root of the underlying XmlDocument
, irrespective of the current node.
Drop the /
and navigate a relative path, and you should be good, i.e.
XmlNode musicNode = xmlDocument.SelectSingleNode("/catalog/music");
XmlNode cdsNode = musicNode.SelectSingleNode("cds");
or just walk the whole path again
XmlNode cdsNode = xmlDocument.SelectSingleNode("/catalog/music/cds");
Upvotes: 2