Noopty
Noopty

Reputation: 167

Comparing attributes of current element and different elements using XSLT

I am trying to compare an attribute of a current element in a loop with all the other attributes. I am not sure if i am doing the right thing so here is my attempt

Here is the XML file:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="sample.xsd">

    <foo>
        <subfoo id="123">Foo 1</subfoo>
        <subfoo id="345">Foo 2</subfoo>
        <subfoo id="678">Foo 3</subfoo>
    </foo>

    <bar id="U123">
        <subbar>Hello World</subbar>
    </bar>

    <bar id="345">
        <subbar>Hello Other World</subbar>
    </bar>

    <bar id="912">
        <subbar>Hello 3rd World</subbar>
    </bar>

</root>

Here is the XSLT file:

  <xsl:template match="root">

            <xsl:variable name="subfoo" select="root/foo/subfoo"/>
            <xsl:variable name="subbar" select="root/bar"/>
            <xsl:for-each select="$subfoo">
                <xsl:variable name="subfooID" select="./@id"/>
                <xsl:for-each select="$subbar">
                    <xsl:if test="$subfooID = ./@id">
                        <xsl:if test="./@id[current()] = @id">
                            <xsl:value-of select="subfoo"/> Matches <xsl:value-of select="subbar"/>
                        </xsl:if>
                    </xsl:if>
                </xsl:for-each>
            </xsl:for-each>

  </xsl:template>

And if the two ID's were matched an output should say something like

Foo 1 Matches Hello World
Foo 2 Matches Hello Other World

Can someone help me find what am i missing here? Regards.

Upvotes: 0

Views: 610

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167561

I would simply define a key for the cross-reference and then process the elements for which there is a cross-reference:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="text"/>

  <xsl:key name="bar" match="bar" use="@id"/>

  <xsl:template match="root">
      <xsl:apply-templates select="foo/subfoo[key('bar', @id)]"/>
  </xsl:template>

  <xsl:template match="subfoo">
      <xsl:value-of select="concat(., ' matches ', key('bar', @id)/subbar, '&#10;')"/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/94hvTzo

In your attempt you have a lots of wrong paths as you don't seem to be aware that an xsl:template or xsl:for-each changes the context so you would need to change e.g. select="root/foo/subfoo" to select="foo/subfoo".

Upvotes: 2

Related Questions