user1803140
user1803140

Reputation: 53

XPath select elements with specific attribute value?

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:

This is the subset of the 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]"

I dont get any results

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

What am I doing wrong?

Best regards, and thanks for any help! Richard

Upvotes: 4

Views: 8804

Answers (1)

John Kugelman
John Kugelman

Reputation: 362147

Use an at sign @ to access attributes:

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

Upvotes: 7

Related Questions