如何使用 XPath 获取 C# 中属性的值?
我想传递一个 xpath 查询并返回我找到的值。 我正在专门寻找属性的值。
_query = "//@RequestType";
我可以取回节点,但我不确定如何从中获取字符串值。 我想查询以下 xml 的 type
属性并获取“xpath”。
如果我可以替换我的查询并从 Nice 返回值“yes”,那就太好了。
<?xml version="1.0" ?>
<test type="xpath">
<nice>yes</nice>
</test>
时间:2019-03-17 标签: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
}
}
}
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
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的 xPath 充其量是很弱的,但请尝试以下操作:
My xPath is weak at best but try the following:
如果您在查询中返回“test”节点,并且它包含一个名为“nice”的子节点,那么您需要从父“test”节点中选择“nice”子节点并返回它的 InnerText,以便获取从中取出“yes”字符串。
我不确定这是否能回答您的问题,因为我认为我没有完全遵循您的要求,但希望这会有所帮助
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 有一个 Value 属性,它将返回当前节点的值作为字符串。如果您已经知道数据的类型,您还可以使用 ValueAsBoolean、ValueAsDateTime 等。
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.