Reputation: 1258
I am trying to convert an XML file to CSV and I am taking help from the following link but struck in a place where I have to retrieve the value from a parent tag and some specific child tag from an XML file. My input XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Payslip>
<StaffNumber>123456</StaffNumber>
<StaffName>ALIBABA</StaffName>
<Sex/>
<PayDetails>
<PayType>NORMAL</PayType>
<AmountNet>2100</AmountNet>
<ComponentDetails>
<ComponentType>SALARY</ComponentType>
<ComponentSource/>
<Code>SAL</Code>
</ComponentDetails>
<ComponentDetails>
<ComponentType>DED</ComponentType>
<ComponentSource/>
<Code>DEN</Code>
</ComponentDetails>
</PayDetails>
<LeaveTaken>
<StartDate/>
<EndDate/>
<Balance>0</Balance>
</LeaveTaken>
</Payslip>
My xsl file looks like this, pls note I have put few hardcoded value for some other requirement.
I'm fairly new to XSLT so please excuse the potential novice question. Any guidance would be appreciated here. Thanks in advance.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" >
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/"> Worker,Pay_Group,Pay_Period_End_Date,Payment_Date,Net_Amount,Gross_Amount,Currency,Ck_Number,Display_Date
<xsl:for-each select="//Payslip">
<xsl:value-of select="concat(StaffNumber,',','PAY_GROUP',',','2017-09-24-00:00',',','2017-09-27-00:00',',',AmountNet,',','AmountGross',',','AUD',',','393',',','SLP000393_',StaffNumber,'.pdf',',','
')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
In the above code if I use
<xsl:for-each select="//Payslip">
then I am getting only StaffNumber and staffName fields but if I use
<xsl:for-each select="//Payslip//PayDetails">
to get value from the AmountNet tag then it fails to fetch value from the StaffNumber tag.
Upvotes: 2
Views: 727
Reputation: 2031
You get only the values of the StaffNumber
and StaffName
because they are direct descendants of the Payslip
node. In order to get the values of the other nodes, you must specify the correct XPath expressions for each of them.
For example in order to get the value of the AmountNet
you should refer to its path as:
PayDetails/AmountNet
instead of just
AmountNet
since the current node inside the for-each loop is the Payslip
node.
Update
Leave the <xsl:for-each select="//Payslip">
to refer the Payslip
node. Just change the line below:
<xsl:value-of select="concat(StaffNumber,',','PAY_GROUP',',','2017-09-24-00:00',',','2017-09-27-00:00',',',AmountNet,',','AmountGross',',','AUD',',','393',',','SLP000393_',StaffNumber,'.pdf',',','
')"/>
to the following:
<xsl:value-of select="concat(StaffNumber,',','PAY_GROUP',',','2017-09-24-00:00',',','2017-09-27-00:00',',',PayDetails/AmountNet,',','AmountGross',',','AUD',',','393',',','SLP000393_',StaffNumber,'.pdf',',','
')"/>
Upvotes: 1