I am new to XSLT and I am working on a small example where I want to transforman XML input file using XSLT to generate a text file.
Here is my input xml file:
<?xml version="1.0" ?>
<result>
<users>
<user>
<user-name>user 1</user-name>
<blood-group>A-</blood-group>
<id>4</id>
<col1>c1</col1>
<col2>c2</col2>
<col4>c4</col4>
</user>
<user>
<user-name>user 2</user-name>
<blood-group>B+</blood-group>
<id>3</id>
<col3>c3</col3>
<col4>c4</col4>
</user>
</users>
</result>
I want to get an output like this after transforming it with XSLT:
User Name | Blood Group | Id | col1 | col2 | col3 | col4
user 1 | A- | 4 | c1 | null | null | null
user 1 | A- | 4 | null | c2 | null | null
user 1 | A- | 4 | null | null | null | c4
user 2 | B+ | 3 | null | null | c3 | null
user 2 | B+ | 3 | null | null | null | c4
The idea is each record will be repeated by the number of col elements the record is having and each line of the output text will have a value for the particular single col element and all other remaining values of col will be null.
I have created an XSL file like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://ift.tt/tCZ8VR"
xmlns:str="http://ift.tt/rkTpc5"
extension-element-prefixes="str">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="/result">
<xsl:text>User Name | Blood Group | Id | col1 | col2 | col3 | col4 </xsl:text>
<xsl:for-each select="users/user">
<xsl:value-of select="str:align(user-name, ' | ', 'left')" />
<xsl:value-of select="str:align(blood-group, ' | ', 'left')" />
<xsl:value-of select="str:align(id, ' | ', 'left')" />
<xsl:value-of select="str:align(col1, ' | ', 'left')" />
<xsl:value-of select="str:align(col2, ' | ', 'left')" />
<xsl:value-of select="str:align(col3, ' | ', 'left')" />
<xsl:value-of select="col4" />
<xsl:if test="position()!=last()">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
With this XSL I got the output as:
User Name | Blood Group | Id | col1 | col2 | col3 | col4
user 1 | A- | 4 | c1 | c2 | | c4
user 2 | B+ | 3 | | | c3 | c4
I am not clear on what functions can be used to get the desired output. Can someone please help me?
The java code that helps me to do the transformation is:
public static void main(String[] args) {
String path="/";
String xml = path+"input.xml";
String xslt = path+"input.xsl";
String output = path+"output.txt";
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer tr = tf.newTransformer(new StreamSource(xslt));
tr.transform(new StreamSource(xml), new StreamResult(
new FileOutputStream(output)));
System.out.println("Output to " + output);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
No comments:
Post a Comment