c# - XPath 选择具有特定属性值的元素?

标签 c# xml select xpath

我在使用 XPath 选择节点时遇到问题。我将展示示例,由于真实数据量大,xml文件被缩短了:

这是 XML 的子集:

<?xml version="1.0" encoding="ISO-8859-1"?>
<design xmlns="namespace_hidden" createddate="2012-12-07" createdby="User" name="New   Design">
  ...
  <variables>
  <measurements>
    <measurement name="Measurement001">
      <sample name="1">
        <position>[0,0]</position>
        <variables>
          <qualitative name="bId">
            <class>2193</class>
          </qualitative>
        </variables>
      </sample>
      ...
      <sample name="4">
        <position>[3,0]</position>
        <variables>
          <qualitative name="Q2">
            <class>V0</class>
          </qualitative>
          <qualitative name="Q3">
            <class>V2</class>
          </qualitative>
          <qualitative name="Q4">
            <class>V1</class>
          </qualitative>
          <quantitative name="Q5">
            <unit>Percent</unit>
            <value>8</value>
          </quantitative>
        </variables>
      </sample>
    </measurement>
    <measurement name="Measurement002">
        ..
    </measurement>
    ...
   </measurements>
</design>

现在,我正在尝试选择特定样本、特定测量下的所有变量。

这是我使用的查询方法:

// Creating the navigator
var doc = new XPathDocument(xmlDoc[0]);
var navigator = doc.CreateNavigator();

// Creating the namespace manager:
XmlNamespaceManager nsMan = null;
if (navigator.NameTable != null) {
     nsMan = new XmlNamespaceManager(navigator.NameTable);
     nsMan.AddNamespace("y", xmlNs);
     nsMan.PushScope();
}

// Executing the query
var iterator = navigator.Select(string.Format("/y:design/y:measurements/y:measurement[name='{0}']/y:sample[name={1}]/y:variables/y:qualitative", currentMeasurement.Name, currentSample.Name), nsMan);

当我使用这个查询时,我得到了第一个测量值和第一个样本,这样就可以了:

string.Format("/y:design/y:measurements/y:measurement[1]/y:sample[1]"

但是如果我使用这个查询:

"/y:design/y:measurements/y:measurement[name='Measurement001']/y:sample[1]"

我没有得到任何结果

无奈之下,我也尝试了围绕属性值的“”的不同组合,但没有成功。

我做错了什么?

此致,感谢您的帮助! 理查德

最佳答案

使用 at 符号 @ 访问属性:

/y:design/y:measurements/y:measurement[@name='Measurement001']/y:sample[1]
                                       ^

关于c# - XPath 选择具有特定属性值的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13841537/

相关文章:

c# - 为什么 System.Convert ("0") 在某些系统上抛出 FormatException?

c# - 如何使用 .wer 文件调试应用程序

Java读取包含内容的XML文件并放入数据库

xml - 我如何使用 Wordpress 修改 YoastSEO 站点地图? (XML 文件)

javascript - 根据所选选项更改输入大小

c# - 想要在文本 block 中显示 slider 的值?

c# - 不减慢任务循环,并知道结果何时返回

c# - 高效解析大型 XML

php - MySQL选择困难

c - 轮询并选择手动轮询[速度]