RXC
RXC

Reputation: 1233

Get corresponding value for specific tag - XML and XSLT

I am using XSLT to parse through an XML document and there is a block that contains repeated element names and I want to grab a certain value that corresponds to a certain tag value. Here is an example of what the xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <tags>
        <tag>
            <tag_id>TEST_TAG1</tag_id>
            <tag_value>TEST_VALUE1</tag_value>
        <tag>
        <tag>
            <tag_id>TEST_TAG2</tag_id>
            <tag_value>TEST_VALUE2</tag_value>
        <tag>
        <tag>
            <tag_id>TEST_TAG3</tag_id>
            <tag_value>TEST_VALUE3</tag_value>
        <tag>
    </tags>
</root>

I am using XSLT 2.0. How can I grab the value "TEST_VALUE2" by checking the tag_id for "TEST_TAG2"?

So basically, I would like to check for a certain tag_id value and save its tag_value value into a variable like this:

    if(tag_id == "TEST_TAG2")
    {
        value = <tag_value> // tag_value element related to the tag_id value TEST_TAG2
    }

Upvotes: 0

Views: 238

Answers (1)

Matthew Green
Matthew Green

Reputation: 10401

The XPath for that would be this

root/tags/tag[tag_id='TEST_TAG2']/tag_value

You can of course adjust that to whatever context you might need it in so long as you use the correct predicate. Otherwise, you just put that into the select of a value-of and that should be it.

Upvotes: 1

Related Questions