简体   繁体   English

如何使用XPath在C#中获取属性的值?

[英]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. 我想传递一个xpath查询并返回我发现的值。 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. 我想查询以下xml的type属性并获取“ xpath”。

It would also be nice if I could just replace my query and also get the value "yes" back from nice. 如果我可以替换查询并从nice中获得值“ yes”,那也很好。

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

c# 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
       }
    }
   }

My xPath is weak at best but try the following: 我的xPath充其量是软弱的,但是请尝试以下操作:

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. 如果您要在查询中重新获得“测试”节点,并且它包含一个名为“ nice”的子节点,则需要从父“测试”节点中选择“ nice”子节点并返回其InnerText以获得字符串“是”。

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. XPathNavigator具有Value属性,该属性将以字符串形式返回当前节点的值。 You can also use ValueAsBoolean, ValueAsDateTime, etc. if you already know the type of your data. 如果您已经知道数据类型,则也可以使用ValueAsBoolean,ValueAsDateTime等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM