【问题标题】:XPath: How to select a node by its attribute?XPath:如何通过属性选择节点?
【发布时间】:2009-07-01 09:33:48
【问题描述】:

我有一个这样的 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;

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

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

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

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

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

    【讨论】:

    • 为什么 0 必须用花括号括起来?我在 Novell IDM 中使用 XPATH,@index=0 在那里就足够了。花括号表示什么?
    • 它不是 xpath 的一部分,它是 String.Format 的一部分,它将被替换为第一个参数(即百分比)
    【解决方案2】:

    顺便说一句,对于我们这些不会说原生 XPath 的人,there are many online XPath "playgrounds" 允许您编写 XML 和 XPath 表达式并在线查看结果。

    每当我发现自己陷入“XPath 地狱”时,我通常会去那些 playgrounds 并尝试各种组合,直到我得到我的(需要的)结果,出于某种原因,它比编写 C# 工作得更快/Python 测试程序甚至运行那些 bloated 所谓的 XML 编辑器。

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多