Benjamin Hundley
Benjamin Hundley

Reputation: 33

Using XPath select all elements that contains a child element with an attribute value

I am trying to use xpath to select all the node elements that contain a child element that has any value for the restriction attribute other than an empty string.

Here is my xml:

<nodes code="C">
   <node code="A">
      <child restriction="" />
      <child restriction="value" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
   </node>
   <node code="B">
      <child restriction="value" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
   </node>
   <node code="C">
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
   </node>
</nodes>

My working xpath is:

nodes/node[(child/@restriction and string-length(child/@restriction) > 0)]

This only returns node B, presumably because B is the only element where the restriction value appears first. My aim is to return both B and A but not C.

Can someone point out where I've gone wrong?

Upvotes: 0

Views: 810

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117100

How about:

nodes/node[child/@restriction[string()]]

This tests each restriction attribute for the existence of a string content.

In your version, you try to convert the node-set of child/@restriction into a string to be used as the argument for string-length(). In XSLT 1.0, this would return the value of the first node in the set; in XSLT 2.0, this would produce an error.

Upvotes: 1

Related Questions