XPath:如何按属性选择节点?

我有一个像这样的XML:

  #FF0000 #FF0200 #FF0300 #FF0500 [..] 

我正在尝试按索引选择节点:

 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; 

我也尝试了注释版本,但它没有返回任何结果。 有什么建议吗?

请改用//color[@index='{0}'] 。 @符号表示“属性”。

我注意到你正在使用逐字字符串文字 – 字符串开头的@符号。 在这种情况下没有必要 – 你在字符串中没有任何反斜杠,并且它不是多行的。 您也不需要在percentage上显式调用ToString – 它将自动转换。

 string xpath = string.Format("//color[@index='{0}']", percentage); 

顺便说一句,对于我们这些不讲原生XPath的人来说, 有许多在线XPath“游乐场”允许您编写XML和XPath表达式并在线查看结果。

每当我发现自己处于“ XPath地狱 ”时,我通常会去那些游乐场并尝试各种组合,直到我得到我的(需要的)结果,由于某种原因它比编写C#/ Python测试程序或甚至运行那些膨胀的所谓XML更快编辑。