Pages

Monday 24 June 2013

Create XML file simple way

This is a simple program that display XML output in console. You can write it separate XML file. 

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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;
import org.w3c.dom.Node;

/**
* By : Anand Maheshwari
*/

public class CreateXMLFile2 {

    public static void main(String[] args) {
        DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder icBuilder;
        try {
            icBuilder = icFactory.newDocumentBuilder();
            Document doc = icBuilder.newDocument();
            Element mainRootElement = doc.createElementNS("http://crunchify.com/iCrunchCreateXMLDOM", "Companies");
            doc.appendChild(mainRootElement);

            // append child elements to root element
            mainRootElement.appendChild(getCompany(doc, "1", "Paypal", "Payment", "1000"));
            mainRootElement.appendChild(getCompany(doc, "2", "eBay", "Shopping", "2000"));
            mainRootElement.appendChild(getCompany(doc, "3", "Google", "Search", "3000"));

            // output DOM XML to console
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult console = new StreamResult(System.out);
            transformer.transform(source, console);

            System.out.println("\nXML DOM Created Successfully..");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Node getCompany(Document doc, String id, String name, String age, String role) {
        Element company = doc.createElement("Company");
        company.setAttribute("id", id);
        company.appendChild(getCompanyElements(doc, company, "Name", name));
        company.appendChild(getCompanyElements(doc, company, "Type", age));
        company.appendChild(getCompanyElements(doc, company, "Employees", role));
        return company;
    }

    // utility method to create text node
    private static Node getCompanyElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }
}

Sunday 23 June 2013

Read XML file using Java

Today i will so you how to read XML file data using Java so that you can further use for other purpose.

First of all you need xmlparserv2.jar  library file that is easily downloadable on net.

This is a XML file look like:

<student>
<person>
  <first>Anand</first>
  <last>Maheshwari</last>
  <age>22</age>
</person>
<person>
  <first>Vivek</first>
  <last>Shah</last>
  <age>21</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</student>

This is Java code for read XML :

package org.anand;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadXMLFile {

    public static void main(String[] args) {
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File("D:/test.xml"));

            // Normalize text representation...
            doc.getDocumentElement().normalize();
            System.out.println("Root element of the doc is : "
                    + doc.getDocumentElement().getNodeName());
            NodeList listOfPersons = doc.getElementsByTagName("person");
            int totalPersons = listOfPersons.getLength();
            System.out.println("Total no of person : " + totalPersons);

            for (int i = 0; i < listOfPersons.getLength(); i++) {
                Node firstPersonNode = listOfPersons.item(i);
                if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) firstPersonNode;

                    // ----------------
                    NodeList firstNameList = firstPersonElement
                            .getElementsByTagName("first");
                    Element firstNameElement = (Element) firstNameList.item(0);

                    NodeList textFNList = firstNameElement.getChildNodes();
                    System.out
                            .println("First Name : "
                                    + ((Node) textFNList.item(0))
                                            .getNodeValue().trim());

                    // ----------------
                    NodeList lastNameList = firstPersonElement
                            .getElementsByTagName("last");
                    Element lastNameElement = (Element) lastNameList.item(0);

                    NodeList textLNList = lastNameElement.getChildNodes();
                    System.out
                            .println("Last Name : "
                                    + ((Node) textLNList.item(0))
                                            .getNodeValue().trim());

                    // ----------------
                    NodeList ageList = firstPersonElement
                            .getElementsByTagName("age");
                    Element ageElement = (Element) ageList.item(0);

                    NodeList textAgeList = ageElement.getChildNodes();
                    System.out.println("Age : "
                            + ((Node) textAgeList.item(0)).getNodeValue()
                                    .trim());

                    // ---------------

                } // End of if clause
            }// end of for loop
        } catch (SAXParseException perr) {
            System.out.println("** parsing error " + ", line"
                    + perr.getLineNumber() + ", uri " + perr.getSystemId());
            System.out.println(" " + perr.getMessage());
        } catch (SAXException se) {
            Exception x = se.getException();
            ((x == null) ? se : x).printStackTrace();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }// end of main
} // end of class

Output Of This program :

Root element of the doc is : student
Total no of person : 3
First Name : Anand
Last Name : Maheshwari
Age : 22
First Name : Vivek
Last Name : Shah
Age : 21
First Name : Steve
Last Name : Jobs
Age : 40

Saturday 15 June 2013

String To Int and Int To String Conversion In Java

       HOW TO CONVERT STRING TO INTEGER AND INTEGER TO STRING IN JAVA

String to Integer Conversion in Java

1 ) By using Integer.parseInt( String str) method.

This is preferred way of converting it, extremely easy and most flexible way of converting String to Integer.

Example :
      // using Integer.parseInt()
      int i = Integer.parseInt("12345");
      System.out.println(i);

This method will throw NumberFormatException if string provided is not a proper number. Same technique can be used to convert data type like float and double to String in Java. Java API provides static methods like Float.parseFloat() and Double.parseDouble() to perform data type conversion.

2 ) Second way, using Integer.valueOf().

Example :
      //How to convert number string = "000000081" into Integer value = 81
      int i = Integer.valueOf("00000081");
      System.out.println(i);

It will ignore the leading zeros and convert the string into int. This method also throws NumberFormatException.

Integer to String Conversion

1 ) Int to String in java using "+" operator
It is a simplest way to convert. Just use "+" operator with int value.

Example
      String price = ""+123;

2 ) Use String.valueOf() method which is static method to convert any integer value to String. In fact String.valueOf(0 method is overloaded to accept almost all primitive type so you can use it convert char, double, float, or any other data type into String.

Example :
      String price = String.valueOf(123);

3 ) Using String.format()
This is a new way of converting an int primitive to String object and introduced in JDK 1.5 along-with several other important features like Enum, Generics and Variable arguments methods. String.format() is even more powerful and can be used in variety of way to format String in Java.

Example :
      String price = String.format("%d",123);