开发者

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

开发者 https://www.devze.com 2023-02-28 16:35 出处:网络
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.

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 Loc开发者_如何转开发ate(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
       }
    }
   }


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


If you are getting the "test" node back in your query and it contains a child node called "nice" then you need to select the "nice" child node from the parent "test" node and return it's InnerText in order to get the string "yes" out of it.

I am not sure that answers your question because I don't think I completely followed what your were asking but hopefully that helps


XPathNavigator has a Value property, which will return the value of the current node as a string. You can also use ValueAsBoolean, ValueAsDateTime, etc. if you already know the type of your data.

0

精彩评论

暂无评论...
验证码 换一张
取 消