2

I need an XPath that will elect all parent nodes a child with anattribute that constains at least one of a list of values.

Example XML

<mynodes>
  <theParentNode>
    <theChildNode name="one two" />
  </theParentNode>
    <theParentNode>
    <theChildNode name="one all" />
  </theParentNode>
    <theParentNode>
    <theChildNode name="two" />
  </theParentNode>
    <theParentNode>
    <theChildNode name="all" />
  </theParentNode>
</mynodes>

I want to select all nodes where name contains "one" OR "all" (or any other combination for that matter). So that the returned nodeList is:

<theParentNode>
  <theChildNode name="one two" />
</theParentNode>
<theParentNode>
  <theChildNode name="one all" />
</theParentNode>
<theParentNode>
  <theChildNode name="all" />
</theParentNode>

So far my query looks like this (note im not using a schema):

//theChildNode[contains(tokenize(@name, '\s'), "one")]

Which will get me all the vendor elements containing "one" in their name attribute. But im unsure how to go about supplying multiple values in place of the "one", and then the best way to step back up to theParentNode. I could always just do all of this in php but id rather just do it with a XPath if possible.

1
  • Why are you using "tokenize"? The "contains" function only operates on strings and will internally concatenate the tokenized string. Commented Jun 25, 2010 at 10:03

3 Answers 3

5

A bit redundant, but this should do it:

//theChildNode[contains(tokenize(@name, '\s'), "one") or contains(tokenize(@name, '\s'), "all")]
Sign up to request clarification or add additional context in comments.

1 Comment

Note to onlookers, tokenize is an unregistered function in XPath 1.0.
1

Not sure about getting the multiple attribute values, but change your selector to

//theParentNode[theChildNode]

to get all parents with the child node.

//theParentNode[theChildNode[contains....]]

No need to step up, select only parents that have the child.

1 Comment

Definitely. Id dont know why i thoughr i couldnt that. Thanks!
1

I don't have an XML test environment available at present, but you might pursue this possibility:

//theChildNode[intersect(tokenize(@name, '\s+'),('one','all'))]

1 Comment

That would be the syntax i would expect and tried initially (only i use | instead of , thinking of an or operator). but got an invalid query (with the , sep as well).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.