XPath的:如何选择其属性的节点? [英] XPath: How to select a node by its attribute?
问题描述
我有一个是这样的XML:
I have an XML that goes like this:
<?xml version="1.0" encoding="utf-8" ?>
<colors>
<color index = "0">#FF0000</color>
<color index = "1">#FF0200</color>
<color index = "2">#FF0300</color>
<color index = "3">#FF0500</color>
[..]
我想选择由它的索引节点:
I'm trying to select a node by its index:
XmlDocument ColorTable = new XmlDocument();
ColorTable.Load(HttpContext.Current.Server.MapPath("~/App_Data/ColorTable.xml"));
int percentage = 2;
string xpath = string.Format(@"//color[index={0}]", percentage.ToString());
//string xpath = string.Format(@"//color[index=""{0}""]", percentage.ToString());
//string xpath = string.Format(@"//color[index='{0}']", percentage.ToString());
var r = ColorTable.SelectSingleNode(xpath).Value;
我也试过了评论的版本,但它不返回任何结果。
任何建议?
I tried also the commented versions, but it does not return any result. Any suggestion?
推荐答案
使用 //颜色[@index ={0} ']
来代替。 。@符号的意思是属性
Use //color[@index='{0}']
instead. The @ sign means "attribute".
我注意到,您使用的是逐字字符串的方式字面 - 在的启动字符串。有没有在这种情况下,没有必要 - 你不必在字符串中的反斜杠,这不是多行。你也不需要显式调用的ToString
在百分比
- 它会自动转换
I note that you're using a verbatim string literal by the way - the @ sign at the start of the string. There's no need in this case - you don't have any backslashes in the string, and it's not multi-line. You also don't need to explicitly call ToString
on percentage
- it will be converted automatically.
string xpath = string.Format("//color[@index='{0}']", percentage);
这篇关于XPath的:如何选择其属性的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!