7

Just getting started here with my first take at XPathNavigator.

This is my simple xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<theroot>
    <thisnode>
        <thiselement visible="true" dosomething="false"/>
        <another closed node />
    </thisnode>

</theroot>

Now, I am using the CommonLibrary.NET library to help me a little:

    public static XmlDocument theXML = XmlUtils.LoadXMLFromFile(PathToXMLFile);

    const string thexpath = "/theroot/thisnode";

    public static void test() {
        XPathNavigator xpn = theXML.CreateNavigator();
        xpn.Select(thexpath);
        string thisstring = xpn.GetAttribute("visible","");
        System.Windows.Forms.MessageBox.Show(thisstring);
    }

Problem is that it can't find the attribute. I've looked through the documentation at MSDN for this, but can't make much sense of what's happening.

bgmCoder
  • 6,205
  • 8
  • 58
  • 105

2 Answers2

12

Two problems here are:

(1) Your path is selecting the thisnode element, but the thiselement element is the one with the attributes and
(2) .Select() does not change the location of the XPathNavigator. It returns an XPathNodeIterator with the matches.

Try this:

public static XmlDocument theXML = XmlUtils.LoadXMLFromFile(PathToXMLFile);

const string thexpath = "/theroot/thisnode/thiselement";

public static void test() {
    XPathNavigator xpn = theXML.CreateNavigator();
    XPathNavigator thisEl = xpn.SelectSingleNode(thexpath);
    string thisstring = xpn.GetAttribute("visible","");
    System.Windows.Forms.MessageBox.Show(thisstring);
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thanks! That's it. I was neglecting to capture the node into a second `XPathNavigator` - I suppose I thought it worked differently. I also found this link, which presents it in an easy fashion too: http://stackoverflow.com/questions/4308118/c-sharp-get-attribute-values-from-matching-xml-nodes-using-xpath-query?rq=1 – bgmCoder May 04 '13 at 03:15
  • @user3240414 tried to ask the following question by editing my answer (please don't do that): _What will be the output for the statement `string thisstring = xpn.GetAttribute("visible",""); Console.WriteLine(thisstring);`_ The output should be `true` in this case. – JLRishe Jan 29 '14 at 14:03
7

You can select a attribute on an element using xpath like this (An alternative to the accepted answer above):

public static XmlDocument theXML = XmlUtils.LoadXMLFromFile(PathToXMLFile);

const string thexpath = "/theroot/thisnode/thiselement/@visible";

public static void test() {
    XPathNavigator xpn = theXML.CreateNavigator();
    XPathNavigator thisAttrib = xpn.SelectSingleNode(thexpath);
    string thisstring = thisAttrib.Value;
    System.Windows.Forms.MessageBox.Show(thisstring);
}
Matt Johnson
  • 1,913
  • 16
  • 23