Search code examples
c#xmldomxpathdocumentxpathnodeiterator

How do I use XPath to get the value of an attribute in c#?


I'd like to pass in an xpath query and return the value of what I find. I'm looking for the value of an attribute specifically.

_query = "//@RequestType";

I can get the node back, but I'm not sure how to get the string value out of it. I want to query the following xml for its type attribute and get "xpath" back.

It would also be nice if I could just replace my query and also get the value "yes" back from nice.

<?xml version="1.0" ?>
<test type="xpath">
   <nice>yes</nice>
</test>

c#

public string Locate(string message)
        {
    using (var stream = new MemoryStream(Encoding.GetBytes(message)))
    {
       var doc = new XPathDocument(stream);
       var nav = doc.CreateNavigator();
       var result = nav.Select(_query);
       if (result != null)
       {
          return result
       }
    }
   }

Solution

  • My xPath is weak at best but try the following:

    var doc = new XPathDocument(stream);
    var nav = doc.CreateNavigator();    
    foreach (XPathNavigator test in nav.Select("test"))
    {
        string type = test.SelectSingleNode("@type").Value;
        string nice = test.SelectSingleNode("nice").Value;
        Console.WriteLine(string.Format("Type: {0} - Nice: {1}", type, nice));
    }