Showing posts with label XML-Java. Show all posts
Showing posts with label XML-Java. Show all posts

Tuesday, July 26, 2011

XML Creation On the Fly - Java Source Code

In my earlier article, I have shown you how to create the XML file using java APIs. Here I will show you how to do the same however without actually creating files. Here I will use the String buffer to hold the XML content that can be used to do further processing if needed.
 @Credit: Sumeet Chakraborty
Java API being used here is same as one earlier.
Another API being used:

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLCreation {

      public static void main(String args[]) {

            XMLCreation xmlCreate = new XMLCreation();
            xmlCreate.createXML();
      }

      private void createXML() {

            String customerName = "Ramesh";
            String customerAddress = "Delhi";

            DocumentBuilder domBuilder = null;
            try {
                  DocumentBuilderFactory domFactory = DocumentBuilderFactory
                              .newInstance();
                  domBuilder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException pcEx) {
                  System.out
                              .println("ParserConfiguration  "
                                          + pcEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured"
                                          + e.getMessage());
            }
            Document newDoc = domBuilder.newDocument();

            // Root element
            Element rootElement = newDoc.createElement("CustomerInformation");
            newDoc.appendChild(rootElement);

            // Creating element containing value Name
            Element curElement = newDoc.createElement("Name");
            curElement.appendChild(newDoc.createTextNode(customerName));
            rootElement.appendChild(curElement);

            // Creating element signifies address
            Element keyElement = newDoc.createElement("Address");
            keyElement.appendChild(newDoc.createTextNode(customerAddress));
            rootElement.appendChild(keyElement);

            DOMSource sourceInt = new DOMSource(newDoc);

           
            //This will hold the XML content being built later on
//This is the difference where we are not creating file
//Instead, we are using StringWriter to hold the XML content
            StringWriter stew = new StringWriter();

            // File stew = new File("C:/sampleXMLfile.xml");

            StreamResult resultInt = new StreamResult(stew);

            TransformerFactory tFactoryInt = TransformerFactory.newInstance();
            Transformer transformerInt = null;

            try {
                  transformerInt = tFactoryInt.newTransformer();
                 
                  //this is where actually transformation happens and creates the XML
                 
                  transformerInt.transform(sourceInt, resultInt);
                  System.out.println("XML created as " + stew.getBuffer().toString());
            } catch (TransformerException tEx) {
                  System.out
                              .println("TransformerException Occured  "
                                          + tEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured                                           + e.getMessage());
            }

      }
}

Create XML File using Java (Source Code)

Hi All,
After so much on the XML front in my blog, I am going to put here the java source code which will create XML file with some dummy data. Guess, it should be the first blog of XML. Nevertheless,  better late than never.

Simple Java Code to create one XML file:
API used:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLCreation {

      public static void main(String args[]) {

            XMLCreation xmlCreate = new XMLCreation();
            xmlCreate.createXML();
      }

      private void createXML() {

            String customerName = "Ramesh";
            String customerAddress = "Delhi";

            DocumentBuilder domBuilder = null;
            try {
                  DocumentBuilderFactory domFactory = DocumentBuilderFactory
                              .newInstance();
                  domBuilder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException pcEx) {
                  System.out
                              .println("ParserConfiguration Exception "
                                          + pcEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured "
                                          + e.getMessage());
            }
            Document newDoc = domBuilder.newDocument();

            // Root element
            Element rootElement = newDoc.createElement("CustomerInformation");
            newDoc.appendChild(rootElement);

            // Creating element containing value of Name
            Element curElement = newDoc.createElement("Name");
            curElement.appendChild(newDoc.createTextNode(customerName));
            rootElement.appendChild(curElement);

            // Creating element signifies address
            keyElement.appendChild(newDoc.createTextNode(customerAddress));
            rootElement.appendChild(keyElement);

            DOMSource sourceInt = new DOMSource(newDoc);


            File stew = new File("C:/sampleXMLfile.xml");

            StreamResult resultInt = new StreamResult(stew);

            TransformerFactory tFactoryInt = TransformerFactory.newInstance();
            Transformer transformerInt = null;

            try {
                  transformerInt = tFactoryInt.newTransformer();
            /* Transformation done here, which actually does the file creation*/   
transformerInt.transform(sourceInt, resultInt);
            } catch (TransformerException tEx) {
                  System.out
                              .println("TransformerException Occured "
                                          + tEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured"
                                          + e.getMessage());
            }

      }
}

Difference between SAX and DOM Parsing in XML

There are very useful differences between SAX and DOM parsing. SAX Parser is the one which is developed to run the java programs especially. Primarily, if we want to extract the data from a xml file once, we should move to SAX, which is one time top to bottom read approach and if we want ot randomly pick the data in an xml file then the tree reperesentation of DOM model is to be put into use.

If we need to find a node and doesnt need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Few top level differences

SAX:
1. Parses node by node
2. Doesnt store the XML in memory
3. We cant insert or delete a node
4. Top to bottom traversing

DOM
1. Stores the entire XML document into memory before processing
2. Occupies more memory
3. We can insert or delete nodes
4. Traverse in any direction.

Source: obviously internet as you all know.

Tuesday, July 19, 2011

Calling Java Methods From XSL While XML Transformation

In my earlier article, I have shown you how to transform a XML from one format to another format.
Below, I will show you how to refer to a Java class from an XSL.

This is the java class which I want to refer to the xsl file. And getDemoProperties() is the method name which I will call from XSL. This is nothing but to get a properties flag value from the properties file.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class DemoProperties {
                 Properties props;
               static String fName = "./DemoProperties.properties";
                   
                    public DemoProperties() {
                        props = new Properties();
                        try {
                                props.load(new FileInputStream(fName));
                        } catch (FileNotFoundException fnfEx){
                                                                fnfEx.printStackTrace();
                        }
                        catch (IOException ioEx){
                            ioEx.printStackTrace();
                        }
                    }
                   
                   
                   
     public String getDemoProperties(String propName) {
                        String retProp=new String("");
                        try {
                            retProp = props.getProperty(propName);
                        } catch(Exception e) {
                                                                e.printStackTrace();
                        }
                        return retProp;
                    }
}

DemoProperties.properties entry.

id=ID1


Input XML file:

       <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
       <Order>
         <CustomerID>0123456789</CustomerID>
         <Title>Mr</Title>
         <FirstName>Vicky</FirstName>
         <Initial>VV</Initial>
         <Surname>Verma</Surname>
         <TelephoneNumber>0987654321</TelephoneNumber>
         <SubPremise>RakhsakNagar</SubPremise>
         <BuildingName>RakhsakNagar</BuildingName>
         <StreetNumber>207</StreetNumber>
         <StreetName>KharadiByPass</StreetName>
         <Locality>Kharadi</Locality>
         <PostTown>Pune</PostTown>
         <County>Pune</County>
         <Postcode>411014</Postcode>
         <OrderDate>20052009 15:18:11</OrderDate>
         <CADDate>05062009 15:23:54</CADDate>
         <OrderReference>022-123456789</OrderReference>
         <DealerChannel>Airtel Voice</DealerChannel>
         <InstallationType>Self</InstallationType>
         <AssetDescription>Airtel TV</AssetDescription>
         <Action>Add</Action>
         <ReplacementType>Active</ReplacementType>
         <CurrentDate>20090611T11:15:08</CurrentDate>
  </Order>



Sample XSL file:
       <?xml version="1.0" encoding="UTF-8" ?>
       <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:rf="DemoProperties">
         <xsl:strip-space elements="*" />
         <xsl:output method="xml" version="1.0" encoding="UTF-8" standalone="yes" indent="yes" />
       <xsl:template match="Order">
       <OrderForProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <xsl:variable name="props" select="rf:new()" />
       <xsl:variable name="var">
         <xsl:value-of select="rf:getCPSProperties($props, 'id')" />
  </xsl:variable>
       <UniqueKey>
       <xsl:attribute name="Id">
         <xsl:value-of select="$var" />
  </xsl:attribute>
         </UniqueKey>
       <ProductsDetails>
         <Product Name="Airtel_TV" />
  </ProductsDetails>
       <PriorSubmission>
         <xsl:attribute name="UserName">AirtelUser</xsl:attribute>
       <xsl:attribute name="SubmitterRef">
         <xsl:value-of select="OrderReference" />
  </xsl:attribute>
  </PriorSubmission>
  </OrderForProduct>
  </xsl:template>
  </xsl:stylesheet>


XMLTransformation.java – Java class which actually does the transformation

import java.io.File;
import java.io.FileOutputStream;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;


public class XMLTransformation {


                XMLTransformation() {

                }
               

                private static void applyTransformAndSave() {
                                 try {
                                                                String sampleInputXML= "SampleInputXML.xml";
                            File sampleInputFile = new File(sampleInputXML);
                                        String sampleOutputXML = "SampleOutputFile.xml";
                            //Convert input file to output batch file according to the XSL
                                        TransformerFactory tFactory1 = TransformerFactory.newInstance();
                                                    Transformer transformer1;
                                                                transformer1 = tFactory1.newTransformer(new StreamSource("SampleXSL.xsl"));
                                                                transformer1.setOutputProperty(OutputKeys.INDENT, "yes");
                            transformer1.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                                                    transformer1.transform(new StreamSource(sampleInputFile), new StreamResult(new FileOutputStream(sampleOutputXML)));
                                                } catch (TransformerConfigurationException tCEx){
                                                                tCEx.printStackTrace();
                        } catch (TransformerException tEx){
                                                                tEx.printStackTrace();
                                                } catch(Exception ex){
                                                                ex.printStackTrace();
                        }
    }



                public static void main(String args[]) {
                                                XMLTransformation xmlTransformation = new XMLTransformation();
                                                XMLTransformation.applyTransformAndSave();
                }

}


Output XML file:

       <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
       <OrderForProduct xmlns:rf="DemoProperties"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <UniqueKey Id="ID1" />
       <ProductsDetails>
         <Product Name="Airtel_TV" />
  </ProductsDetails>
        <PriorSubmission UserName="AirtelUser" SubmitterRef="022-123456789" />
  </OrderForProduct>

Total Pageviews