Friday, 17 October 2014

DOM: Append new child to given document

Document class provides "appendChild” method to add newChild to the end of the list of children of this node.

Let’s say employee.xml looks like below. This post explains you how to add a new employee details to the document.

<?xml version='1.0' encoding='UTF-8'?>

<!ELEMENT employees (employee)*>

<!ELEMENT employee (address,lastname,firstname)>
<!ATTLIST employee id ID #REQUIRED>

<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT address (country,state,city,area)>
<!ATTLIST address type CDATA #REQUIRED>

<!ELEMENT area (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT country (#PCDATA)>


employee.xml
<?xml version="1.0"?>
<!DOCTYPE books SYSTEM "employee.dtd">

<employees>

  <employee id="1" type="permanent">
    <firstname>Hari Krishna</firstname>
    <lastname>Gurram</lastname>
    <address type="permanent">
      <area>Marthali</area>
      <city>Bangalore</city>
      <state>Karnataka</state>
      <country>India</country>
    </address>
  </employee>
  
  <employee id="2" type="permanent">
    <firstname>Joel Babu</firstname>
    <lastname>Chelli</lastname>
    <address type="temporary">
      <area>Jubli Hills</area>
      <city>Hyderababd</city>
      <state>Andhra Pradesh</state>
      <country>India</country>
    </address>
  </employee>
  
  <employee id="3" type="contract">
    <firstname>Susantha</firstname>
    <lastname>Sarm</lastname>
    <address type="permanent">
      <area>Gandhi Nagar</area>
      <city>Bhuvaneswar</city>
      <state>Orissa</state>
      <country>India</country>
    </address>
  </employee>

</employees>


I want to add one more employee “Murali Krishna”  details to the above document and save the data to some other file.

<employee id="4" type="contract">
    <firstname>Murali Krishna</firstname>
    <lastname>Bachu</lastname>
    <address type="permanent">
      <area>Laxmi circle</area>
      <city>Guntur</city>
      <state>Andhra Pradesh</state>
      <country>India</country>
    </address>
</employee>


To make it generalize i want to create Address class to store address data, and Employee class to store Employee data.

public class Address {
    private String type;
    private String area;
    private String city;
    private String state;
    private String country;

    public String getArea() {
        return area;
    }

    public String getCity() {
        return city;
    }

    public String getCountry() {
        return country;
    }

    public String getState() {
        return state;
    }

    public String getType() {
        return type;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public void setState(String state) {
        this.state = state;
    }

    public void setType(String type) {
        this.type = type;
    }
}


Employee.java
public class Employee {
    private String firstName;
    private String lastName;
    private String type;
    private String id;
    private Address addrees;

    public Address getAddrees() {
        return addrees;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getType() {
        return type;
    }

   public String getId() {
        return id;
    }


    public void setAddrees(Address addrees) {
        this.addrees = addrees;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setId(String id) {
        this.id = id;
    }
}


DomParser.java
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.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class DomParser {

    static Document parseDoc(String doc) throws ParserConfigurationException, SAXException, IOException{
        /* 1. Get the instance of BuilderFactory class. */
        DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();

        /* 2. Instantiate DocumentBuilder object. */
        DocumentBuilder docBuilder = builder.newDocumentBuilder();

        /* Get the Document object  */
        Document document = docBuilder.parse("employee.xml");

        return document;
    }

    static void addNewEmployee(Document doc, Employee emp){
        Element employee = doc.createElement("employee");
        employee.setAttribute("id", emp.getId());
        employee.setAttribute("type", emp.getType());

        /* Create firstname elment and add it to employee element */
        Element firstName = doc.createElement("firstname");
        firstName.setTextContent(emp.getFirstName());
        employee.appendChild(firstName);

        /* Create lastname elment and add it to employee element */
        Element lastName = doc.createElement("lastname");
        lastName.setTextContent(emp.getLastName());
        employee.appendChild(lastName);

        /* Create firstname elment and add it to employee element */
        Element address = doc.createElement("address");
        address.setAttribute("type", emp.getAddrees().getType());
        employee.appendChild(address);

        /* Create firstname elment and add it to employee element */
        Element area = doc.createElement("area");
        area.setTextContent(emp.getAddrees().getArea());
        address.appendChild(area);

        /* Create firstname elment and add it to employee element */
        Element city = doc.createElement("city");
        city.setTextContent(emp.getAddrees().getCity());
        address.appendChild(city);

        /* Create firstname elment and add it to employee element */
        Element state = doc.createElement("state");
        state.setTextContent(emp.getAddrees().getState());
        address.appendChild(state);

        /* Create firstname elment and add it to employee element */
        Element country = doc.createElement("country");
        country.setTextContent(emp.getAddrees().getCountry());
        address.appendChild(country);

        doc.getElementsByTagName("employees").item(0).appendChild(employee);
    }

    static void saveDocument(Document doc) throws TransformerConfigurationException, TransformerException{
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Result output = new StreamResult(new File("output.xml"));
        Source input = new DOMSource(doc);
        transformer.transform(input, output);
    }

    public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException{
        
        /* Get the document */
        Document document = parseDoc("employee.xml");

        /* Populate Employee and adress properties */
        Address addr = new Address();
        addr.setArea("Laxmi circle");
        addr.setCity("Guntur");
        addr.setCountry("India");
        addr.setState("Andhra Pradesh");
        addr.setType("permanent");

        Employee emp = new Employee();
        emp.setAddrees(addr);
        emp.setFirstName("Murali Krishna");
        emp.setLastName("Bachu");
        emp.setId("4");
        emp.setType("permanent");
        
        /* Add Employee to document */
        addNewEmployee(document, emp);

        /* Save the document */
        saveDocument(document);
    }
}


When you ran above program ”output.xml” is created by appending new employee “Murali Krishna” details.

Output.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees>

  <employee id="1" type="permanent">
    <firstname>Hari Krishna</firstname>
    <lastname>Gurram</lastname>
    <address type="permanent">
      <area>Marthali</area>
      <city>Bangalore</city>
      <state>Karnataka</state>
      <country>India</country>
    </address>
  </employee>
  
  <employee id="2" type="permanent">
    <firstname>Joel Babu</firstname>
    <lastname>Chelli</lastname>
    <address type="temporary">
      <area>Jubli Hills</area>
      <city>Hyderababd</city>
      <state>Andhra Pradesh</state>
      <country>India</country>
    </address>
  </employee>
  
  <employee id="3" type="contract">
    <firstname>Susantha</firstname>
    <lastname>Sarm</lastname>
    <address type="permanent">
      <area>Gandhi Nagar</area>
      <city>Bhuvaneswar</city>
      <state>Orissa</state>
      <country>India</country>
    </address>
  </employee>

  <employee id="4" type="permanent">
    <firstname>Murali Krishna</firstname>
    <lastname>Bachu</lastname>
    <address type="permanent">
      <area>Laxmi circle</area>
      <city>Guntur</city>
      <state>Andhra Pradesh</state>
      <country>India</country>
    </address>s
  </employee>
</employees>





 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment