XPath 和 XPathSelectElement
我有以下 xml
<root>
<databases>
<db1 name="Name1" />
<db2 name="Name2" server="myserver" />
<db3 name="Name3" />
</databases>
<root>
我已经尝试了所有可能的 XPath 查询组合来读取 db2 的名称(=“Name2”),但从未获得预期的结果。
到目前为止我的代码:
var query = "root/databases/db2.. "; // here I've tried everything
var doc = XDocument.Load("myconfig.xml");
var dbName = doc.XPathSelectElement(query);
获取我的“Name2”(属性的值)的正确查询是什么?
感谢您的帮助。
I have the following xml
<root>
<databases>
<db1 name="Name1" />
<db2 name="Name2" server="myserver" />
<db3 name="Name3" />
</databases>
<root>
I've tried everything to read the name of the db2 (="Name2") with all possible combinations of XPath queries, but never get the expected result.
My Code so far:
var query = "root/databases/db2.. "; // here I've tried everything
var doc = XDocument.Load("myconfig.xml");
var dbName = doc.XPathSelectElement(query);
What's the correct query to get my "Name2" (the value of the Attribute) ?
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
XPathSelectElement 方法 只能用于选择元素,而不能用于选择属性。
对于属性,您需要使用更通用的 XPathEvaluate 方法:
The XPathSelectElement method can only be used to select elements, not attributes.
For attributes, you need to use the more general XPathEvaluate method:
要获取
db2
元素的name
属性的值 (Name2
),请尝试以下操作:如果您不知道元素 (
db2
),但确实知道它有一个server
属性,请尝试以下操作:如果您想要执行与上一个示例相同的操作,但有多个具有
server
属性的元素,并且您想要在那些,试试这个:To get the value (
Name2
) of thename
attribute, of thedb2
element, try this:If you don't know the name of the element (
db2
), but do know that it has aserver
attribute, try this:If you want to do the same thing as the previous example, but there are multiple elements with a
server
attribute, and you want to pick between those, try this: