繁体   English   中英

XPath:如何通过其属性选择节点?

[英]XPath: How to select a node by its attribute?

我有一个像这样的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>
  [..]

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

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 hell ”时,我通常会去那些游乐场并尝试各种组合,直到我得到我的(需要的)结果,由于某种原因它比编写C#/ Python测试程序或甚至运行那些膨胀的所谓XML更快编辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM