Translating from One XML Schema to Another xml using java



An XSLT style sheet can be applied to translate data from one XML grammar to another. Suppose that you receive stock quotes marked up in the following format:
<?xml version="1.0"?>
<investments>
  <item type="stock" exch="nyse"   symbol="ZCXM" company="kartik corp"
        price="28.875"/>
  <item type="stock" exch="nasdaq" symbol="ZFFX" company="chandra inc"
        price="92.250"/>
  <item type="stock" exch="nasdaq" symbol="ZYSZ" company="mandal inc"
        price="20.313"/>
</investments>
You want to add this information to your portfolio of the following format.
<?xml version="1.0"?>
<portfolio>
  <stock exchange="nyse">
    <name>kartik corp</name>
    <symbol>ZCXM</symbol>
    <price>28.875</price>
  </stock>
  <stock exchange="nasdaq">
    <name>chandra inc</name>
    <symbol>ZFFX</symbol>
    <price>92.250</price>
  </stock>
  <stock exchange="nasdaq">
    <name>mandal inc</name>
    <symbol>ZYSZ</symbol>
    <price>20.313</price>
  </stock>
</portfolio>
This amounts to translating from one XML schema to another. You can use XSLT to transform the <investments> data into the <portfolio>grammar. When you do this, your templates will contain output elements such as <stock>, instead of HTML elements. The following XSLT style sheet is an example.
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
  <portfolio>
    <xsl:for-each select="investments/item[@type='stock']">
      <stock>
        <xsl:attribute name="exchange">
            <xsl:value-of select="@exch"/>
        </xsl:attribute>
        <name><xsl:value-of select="@company"/></name>
        <symbol><xsl:value-of select="@symbol"/></symbol>
        <price><xsl:value-of select="@price"/></price>
      </stock>
    </xsl:for-each>
  </portfolio>
</xsl:template>

</xsl:stylesheet>
The translation can be performed in reverse with a similar style sheet, converting <portfolio> data to the <investments> grammar.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
  <investments>
    <xsl:for-each select="portfolio/stock">
      <item type="stock">
        <xsl:attribute name="exch"><xsl:value-of select="@exchange"/></xsl:attribute>
        <xsl:attribute name="symbol"><xsl:value-of select="symbol"/></xsl:attribute>
        <xsl:attribute name="company"><xsl:value-of select="name"/></xsl:attribute>
        <xsl:attribute name="price"><xsl:value-of select="price"/></xsl:attribute>
      </item>
    </xsl:for-each>
  </investments>
</xsl:template>

</xsl:stylesheet>



package com.kartik.xml.to.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XmlToXmlConvert {

    public static void main(String[] args)

    {
        String dataXML = convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\xxx.xml");
       
        Templates input =createTemplate();

        XmlToXmlConvert st = new XmlToXmlConvert();
        
        System.out.println(st.transform(dataXML, input));

       /* String inputXSL = convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\breakFirst.xslt");

        String outputHTML = "C:\\Users\\kmandal\\Desktop\\break.html";
         try{
            st.transform(dataXML, inputXSL, outputHTML);
        }catch (TransformerConfigurationException e){

            System.err.println("TransformerConfigurationException");

           // System.err.println(e);

        }catch (TransformerException e){
            System.err.println("TransformerException");
           // System.err.println(e);

        }*/

    }

 

    public void transform(String dataXML, String inputXSL, String outputHTML)throws TransformerConfigurationException,TransformerException

    {
        TransformerFactory factory = TransformerFactory.newInstance();

        StreamSource xslStream = new StreamSource(inputXSL);

        Transformer transformer = factory.newTransformer(xslStream);

        StreamSource in = new StreamSource(dataXML);

        StreamResult out = new StreamResult(outputHTML);

        transformer.transform(in, out);

        System.out.println("The generated HTML file is:" + outputHTML);

    }
    
    /**
     * Transform xml using pfile to String
     * @param xmlDataInput
     * @param xsltTemplate
     * @return
     */
    public String transform(String xmlDataInput, Templates xsltTemplate) {
        if ( xmlDataInput == null || xmlDataInput.trim().length() == 0 || xsltTemplate == null) {
            return null;
        }
  StringWriter stringWriter = new StringWriter();
  try {
   Transformer transformer = xsltTemplate.newTransformer();
   StreamSource source = new StreamSource(new StringReader(xmlDataInput));

   javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(
     stringWriter);
   transformer.transform(source, result);
  } catch (TransformerConfigurationException tce) {
   throw new RuntimeException("Error in XSLT rule transformation");
  } catch (TransformerException te) {
   throw new RuntimeException("Error in XSLT rule transformation");
  }

  return stringWriter.getBuffer().toString();
 }
    /**
     * 
     * @return
     */
    public static Templates createTemplate(){
     TransformerFactory tFactory = TransformerFactory.newInstance();
       // String xslt = getXslt();//this is read from properties file
        String xslt = convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\xxx.xslt");
           if ( xslt != null ) {
               StreamSource stylesource = new StreamSource(new StringReader(xslt));
               try {
                return tFactory.newTemplates(stylesource);
               } catch (TransformerConfigurationException e) {
                 System.out.println("Error");
               }
           }
           return null;
    }
    /**
     * 
     * @param fileName
     * @return
     */
    public static String convertXMLFileToString(String fileName) 
    { 
      try{ 
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
        InputStream inputStream = new FileInputStream(new File(fileName)); 
        org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream); 
        StringWriter stw = new StringWriter(); 
        Transformer serializer = TransformerFactory.newInstance().newTransformer(); 
        serializer.transform(new DOMSource(doc), new StreamResult(stw)); 
        return stw.toString(); 
      } 
      catch (Exception e) { 
        e.printStackTrace(); 
      } 
        return null; 
    }

}

         




Previous
Next Post »