Search code examples
variablesxsltposition

xslt finding position of a specific element in a variable


I have a global variable name="cats" as="element()*. The data I used to create the variable and the data I want to transform are in different parts of the tree of the document.
Let's say the variable contains the elements CellA, CellF and CellC (enclosed in <Item> tags).

My goal is to fill the following predefined structure with data from a table which contains as many cells <field> per <line> as the variable (and in the same order).

<row>
    <CellA> </CellA>
    <CellB> </CellB>
    <CellC> </CellC>
    <CellD> </CellD>
    <CellE> </CellE>
    <CellF> </CellF>
</row>

My idea is to check for each <Cell_> if the name exists in the variable and use its position to access the original data.
Unfortunately, I cannot use position() while looping through $cats because I am not able to access <field> here.

Another method, which was suggested elsewhere, would be to count the number of preceding-siblings where $cats = Cell_. However, the suggestion was not based on variables. And (due to being a novice) I was not able to figure out how to do this.
Is it possible to do it this way? Is there another way to do it?

If something is not clear, please let me know.

Additional information

sourceXML

<body>
    <line>
        <field>data</field>
        <field/>
        <field/>
    </line>
    <line/>
    ...
</body>

targetXML (see above)

XSLT

<xsl:variable name="cats" as="element()*">
    <Item>CellA</Item>
    <Item>CellF</Item>
    <Item>CellC</Item>
</xsl:variable>
<xsl:for-each select="body/line">
    <row>
        <CellA>
            *What to do here to fill it with data from source xml*
            <xsl:variable name="pos" select="???"/>
            <xsl:value-of select="field[$pos]"/>
        </CellA>
        <CellB>
        </CellB>
        ...
    </row>

Solution

  • My idea is to check for each <Cell_> if the name exists in the variable and use its position to access the original data.

    Apparently you want to use the index-of() function.