Sunday, September 15, 2013

Java Xml modify

package Utility;

/**
 *
 * @author Sakib
 */
import java.io.File;
import java.io.IOException;
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;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

    public static void main(String argv[]) {

       try {
        String filepath = "c:\\temp\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // Get the root element
        Node company = doc.getFirstChild();

        // Get the staff element , it may not working if tag has spaces, or
        // whatever weird characters in front...it's better to use
        // getElementsByTagName() to get it directly.
        // Node staff = company.getFirstChild();

        // Get the staff element by tag name directly
        Node staff = doc.getElementsByTagName("staff").item(1);

        // update staff attribute
        NamedNodeMap attr = staff.getAttributes();
        Node nodeAttr = attr.getNamedItem("id");
        nodeAttr.setTextContent("2");

        // append a new node to staff
        Element age = doc.createElement("age");
        age.appendChild(doc.createTextNode("28"));
        staff.appendChild(age);

        // loop the staff child node
        NodeList list = staff.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {

                   Node node = list.item(i);

           // get the salary element, and update the value
           if ("salary".equals(node.getNodeName())) {
            node.setTextContent("2000000");
           }

                   //remove firstname
        //   if ("firstname".equals(node.getNodeName())) {
        //    staff.removeChild(node);
        //   }

        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

       } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
       } catch (TransformerException tfe) {
        tfe.printStackTrace();
       } catch (IOException ioe) {
        ioe.printStackTrace();
       } catch (SAXException sae) {
        sae.printStackTrace();
       }
    }
}

Java XML Read


package Utility;

/**
 *
 * @author Sakib
 */


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFile {

   public static void main(String argv[]) {

    try {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

    boolean bfname = false;
    boolean blname = false;
    boolean bnname = false;
    boolean bsalary = false;

    public void startElement(String uri, String localName,String qName,
                Attributes attributes) throws SAXException {

        System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("FIRSTNAME")) {
            bfname = true;
        }

        if (qName.equalsIgnoreCase("LASTNAME")) {
            blname = true;
        }

        if (qName.equalsIgnoreCase("NICKNAME")) {
            bnname = true;
        }

        if (qName.equalsIgnoreCase("SALARY")) {
            bsalary = true;
        }

    }

    public void endElement(String uri, String localName,
        String qName) throws SAXException {

        System.out.println("End Element :" + qName);

    }

    public void characters(char ch[], int start, int length) throws SAXException {

        if (bfname) {
            System.out.println("First Name : " + new String(ch, start, length));
            bfname = false;
        }

        if (blname) {
            System.out.println("Last Name : " + new String(ch, start, length));
            blname = false;
        }

        if (bnname) {
            System.out.println("Nick Name : " + new String(ch, start, length));
            bnname = false;
        }

        if (bsalary) {
            System.out.println("Salary : " + new String(ch, start, length));
            bsalary = false;
        }

    }

     };

       saxParser.parse("c:\\temp\\file.xml", handler);

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

   }

}