C# XPath:如何通过属性选择节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1068210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XPath: How to select a node by its attribute?
提问by pistacchio
I have an XML that goes like this:
我有一个像这样的 XML:
<?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?
我也尝试了评论版本,但它没有返回任何结果。有什么建议吗?
采纳答案by Jon Skeet
Use //color[@index='{0}']
instead. The @ sign means "attribute".
使用//color[@index='{0}']
来代替。@ 符号的意思是“属性”。
I note that you're using a verbatim string literal by the way - the @ sign at the startof 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.
我注意到,顺便说一下,您正在使用逐字字符串文字 -字符串开头的 @ 符号。在这种情况下没有必要 - 字符串中没有任何反斜杠,而且它不是多行的。你也不需要显式调用ToString
上percentage
-它会自动转换。
string xpath = string.Format("//color[@index='{0}']", percentage);
回答by Shay Erlichmen
BTW, for those of us who doesn't speak native XPath, there are many online XPath "playgrounds"that allow you to write XML and XPath expression and see the results online.
顺便说一句,对于我们这些不会说原生 XPath 的人来说,有许多在线 XPath“游乐场”允许您编写 XML 和 XPath 表达式并在线查看结果。
Whenever I found myself in a "XPath hell" I usually go to those playgroundsand try various combination till I get my (needed) results, for some reason it works faster than writing C#/Python test program or even running those bloatedso called XML editors.
每当我发现自己处于“ XPath 地狱”中时,我通常会去那些操场尝试各种组合,直到我得到(需要的)结果,出于某种原因,它比编写 C#/Python 测试程序甚至运行那些臃肿的所谓 XML更快编辑。