0

I have an XML file with the following content:

<option>
      <test attr="a">text1</test>
      <test attr="b">text2</test>
      <test attr="c">text3</test>
</option>

How can I now extract text2 using xslt? Everything I try gives me text1.

For example:

<xsl:if test="option/test/@attr='a'">
<xsl:value-of select="option/test"/>
</xsl:if>
0

2 Answers 2

1

This XPath should get you the text2 value:

option/test[@attr='b']

It effectively says "select the test element that has an attr attribute with a value of 'b'".

So you could use it like this:

<xsl:value-of select="option/test[@attr='b']"/>

without the need for the xsl:if.

Sign up to request clarification or add additional context in comments.

4 Comments

That will find <test> elements anywhere in the document, not just those which are children of the <option> element. Generally, // is overkill unless you really do want a global search.
@keshlam while that is very true, and a good point, considering that the OP states this is the content of their XML I felt that it was allowable in this case. It's the predicate that is the point I am trying to get across, hence the explanation.
Since the OP doesn't know how to use a predicate I think it would be safe to assume they wouldn't know the issues with using the double slashes either. In that case I would either clearly state what that is doing or use a more efficient XPath. We don't want them to learn bad habits.
@MatthewGreen Very fair point - I've edited my answer accordingly.
1

You need to use a predicate to specify "the test whose attr has the value 'a'".

 option/test[@attr='a']   

You also need to be aware of the difference between relative and absolute xpaths, and know what context you're invoking the path from -- you are using relative paths which will work only if your current node is the option's parent.

2 Comments

Your XPath will select the element with text1, not the element with text2 as required by the OP.
The OP's question referred to both 'a' and text2. Rather that waste time reconciling that, I flipped a coin and trusted that if I was wrong the relevant change was obvious.

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.