Ashwini
Ashwini

Reputation: 41

Get input XML tags name in XML output applying XSLT in java

I'm new to xslt.

What I want is get the tag names from input xml by applying xslt and save the output in output.xml

My input.xml is -

<?xml version="1.0" encoding="UTF-8"?>
<productDetails>
<name>Mobile</name>
<price>999</price>
<stock>57</stock>
</productDetails>

My input.xsl is -

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>

<xsl:template match="/productDetails">
   <xsl:attribute name="name()"/>   
</xsl:template>
</xsl:stylesheet>

My java code is -

   Source xmlInput = new StreamSource("input.xml");
    Source xsl = new StreamSource(new File("input.xsl"));
    Result xmlOutput = new StreamResult(new File("output.xml"));


        Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
        transformer.transform(xmlInput, xmlOutput);

Output what I want is -

<?xml version="1.0" encoding="UTF-8"?>
 name
 price
 stock

Please anyone help

Thank you in advance.

Upvotes: 0

Views: 629

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

Write a template

<xsl:template match="*">
  <xsl:value-of select="name()"/>
</xsl:template>

if you want to output the name of all elements in the input. If you only need the name of the leaf elements then use

<xsl:template match="*[not(*)]">
  <xsl:value-of select="name()"/>
</xsl:template>

You might need or want to add white space for better formatting of the result. And not that you said you want an XML result yet the result sample you showed with the pure text nodes at the main level is not a well-formed XML document. XSLT however allows the output of such fragments so if that format is what you want my suggestion should do.

Upvotes: 1

Related Questions