I have a XML file of:
<?xml version="1.0" encoding="utf-8"?>
<Batch BatchID="896" BatchName="20120629.130504">
<Document DocumentType="XML Question">
<Fields>
<Field FieldName="Doc_ID">1</Field>
<Field FieldName="Vendor_Code">126400</Field>
<Field FieldName="Property_Code">10519</Field>
<Field FieldName="Invoice_Num">20509</Field>
</Fields><Files />
</Document>
</Batch>
and I want to convert it to look something like below using an XSLT file:
<?xml version="1.0" standalone="yes"?>
<ABCRelease>
<ABC>
<Doc_Id>1345</Doc_Id>
<Vendor_Code>134500</Vendor_Code>
<Property_Code>105559</Property_Code>
<Invoice_Num>2034539</Invoice_Num>
</ABC>
</ABCRelease>
My first time playing with XML and I have spent many hours not getting to far today and done a lot of searching on the topic. Is anyone able to help me out and provide some sample code that would enable this?
My problem has been in extracting the FieldName value and inserting it in the <> eg from:
<Field FieldName="Doc_ID">1</Field>
to
<Doc_Id>1345</Doc_Id>
Really would appreaciate your help.
Steven
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="Fields">
<ABCRelease>
<ABC>
<xsl:apply-templates/>
</ABC>
</ABCRelease>
</xsl:template>
<xsl:template match="Field">
<xsl:element name="{@FieldName}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<Batch BatchID="896" BatchName="20120629.130504">
<Document DocumentType="XML Question">
<Fields>
<Field FieldName="Doc_ID">1</Field>
<Field FieldName="Vendor_Code">126400</Field>
<Field FieldName="Property_Code">10519</Field>
<Field FieldName="Invoice_Num">20509</Field>
</Fields>
<Files />
</Document>
</Batch>
produces the wanted, correct result:
<ABCRelease>
<ABC>
<Doc_ID>1</Doc_ID>
<Vendor_Code>126400</Vendor_Code>
<Property_Code>10519</Property_Code>
<Invoice_Num>20509</Invoice_Num>
</ABC>
</ABCRelease>
Explanation:
Proper use of <xsl:element> and AVTs (Attribute Value Templates).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With