Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting parent element in XSLT

Tags:

xml

xslt

xpath

I have an XML like this:

<PurchaseOrder>
    <ID>1</ID>
    <PurchaseOrderLine>
        <DATA>100<DATA>
    </PurchaseOrderLine>
    <PurchaseOrderLine>
        <DATA>200<DATA>
    </PurchaseOrderLine>
    <PurchaseOrderLine>
        <DATA>300<DATA>
    </PurchaseOrderLine>
</PurchaseOrder>
<PurchaseOrder>
    <ID>2</ID>
    <PurchaseOrderLine>
        <DATA>100<DATA>
    </PurchaseOrderLine>
    <PurchaseOrderLine>
        <DATA>200<DATA>
    </PurchaseOrderLine>
    <PurchaseOrderLine>
        <DATA>300<DATA>
    </PurchaseOrderLine>
</PurchaseOrder>
<PurchaseOrder>
    <ID>3</ID>
    <PurchaseOrderLine>
        <DATA>100<DATA>
    </PurchaseOrderLine>
    <PurchaseOrderLine>
        <DATA>200<DATA>
    </PurchaseOrderLine>
    <PurchaseOrderLine>
        <DATA>300<DATA>
    </PurchaseOrderLine>
</PurchaseOrder>

and XSL:

<xsl:template match="PurchaseOrder">
    <xsl:apply-templates select="PurchaseOrderLine"/>
</xsl:template>

<xsl:template match="PurchaseOrderLine">
    <!-- I want to get the PurchaseOrder\ID here for the current PurchaseOrder -->
</xsl:template>

How can I get current parent element value (PurchaseOrder\ID) in PurchaseOrderLine?

like image 547
VextoR Avatar asked Oct 02 '12 07:10

VextoR


2 Answers

If you want your templates to be atomic (isolated and reusable), you should be referencing a parent node this way. Instead, when calling the template, pass in the reference you want to be able to use. This way you could use this template for the same type of node, even if it has a different context/parent (so long as you can still load the parameter).

<xsl:template match="PurchaseOrder">
    <xsl:apply-templates select="PurchaseOrderLine">
        <xsl:with-param name="PurchaseOrder" select="."/>
    </xsl:apply-templates>
</xsl:template>

<xsl:template match="PurchaseOrderLine">
    <xsl:param name="PurchaseOrder"/>
    <!-- I want to get the PurchaseOrder\ID here for the current PurchaseOrder -->
</xsl:template>

Now in your PurchaseOrderLine template, you can reference the $PurchaseOrder variable.

like image 84
rainabba Avatar answered Sep 25 '22 15:09

rainabba


Seems like you have skipped some basic reading on XPath.

<xsl:template match="PurchaseOrderLine">
    <xsl:value-of select="../ID" />
</xsl:template>
like image 43
Tomalak Avatar answered Sep 24 '22 15:09

Tomalak