Getting Parent Element in XSLT

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 the current value of the parent item (PurchaseOrder \ ID) in PurchaseOrderLine?

+8
source share
3 answers

It looks like you missed the basic reading on XPath.

 <xsl:template match="PurchaseOrderLine"> <xsl:value-of select="../ID" /> </xsl:template> 
+3
source

If you want your templates to be atomic (isolated and reusable), you must reference the parent node in this way. Instead, when invoking the template, pass the link that you want to use. This way you can use this template for the same node type, even if it has a different context / parent (so far 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.

+11
source

Not sure if this is where you are going, but you can map the parent node by doing the following: it checks to see if the parent node has a child node.

 <xsl:template match="//*[PurchaseOrderLine]> <!--- Do you stuff here with parent context---> </xsl:template> 

There are several things you can do, you can choose PurchaseOrderLine with an identifier and data value.

 <xsl:template match="//PurchaseOrder[ID=3 and PurchaseOrderLine/DATA=100]"> <!--- Do stuff with parent that has the ID of 3 And the DATA of 200 ---> </xsl:template> 
0
source

All Articles