XPath是否选择具有特定属性值的元素? [英] XPath select elements with specific attribute value?

查看:94
本文介绍了XPath是否选择具有特定属性值的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在选择XPath节点时遇到问题.我将显示示例,由于实际文件中的大量数据,xml文件被缩短了:

I'm having problems selecting nodes with XPath. I'll show the example, xml file is shortened due to the extensive amount of data in the real one:

这是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>

现在,我正在尝试选择特定样本和特定度量下的所有变量.

Now, im trying to select all variables under a specific sample, under a specific measurement.

这是我使用的查询方法:

This is the querying method I use:

// 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);

当我使用此查询时,我得到了第一个测量值和第一个样本,因此可以工作:

When I use this query I get the first measurement and the first sample, so that works:

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

但是如果我使用此查询:

but if I use this query:

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

我没有得到任何结果

无奈之下,我还尝试了围绕属性值使用''的不同组合,但均未成功.

In desperation I have also tried different combinations of '' around the attribute values to no success.

我在做什么错了?

最诚挚的问候,感谢您的帮助! 理查德

Best regards, and thanks for any help! Richard

推荐答案

使用符号@来访问属性:

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

这篇关于XPath是否选择具有特定属性值的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆