Friday, 17 January 2014

Unknown

How to write XML file in java


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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteFormattedXmlExample
{

  public static void main(String[] args) throws Exception
  {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root element
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);

    // staff element
    Element employee = doc.createElement("employee");
    rootElement.appendChild(employee);

    // set attribute to staff element
    Attr attr = doc.createAttribute("id");
    attr.setValue("1001");
    employee.setAttributeNode(attr);

    // shorten way
    // staff.setAttribute("id", "1");

    // firstname elements
    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("vipul"));
    employee.appendChild(firstname);

    // lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("vaghela"));
    employee.appendChild(lastname);

    // nickname elements
    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("vip"));
    employee.appendChild(nickname);

    // salary elements
    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("2000000"));
    employee.appendChild(salary);

    // write xml to file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");

    DOMSource source = new DOMSource(doc);

    StreamResult result = new StreamResult(new File("file.xml"));

    // Show output on console during development
    //StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("Xml File saved!");

  }
}
Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <employee id="1001">
    <firstname>vipul</firstname>
    <lastname>vaghela</lastname>
    <nickname>vip</nickname>
    <salary>200000</salary>
  </employee>
</company>

Unknown

About Blog No Baap -

Since 2016 BlogNoBaap has been bringing you the very best in all types of web resources. Posted daily, and delivered straight to your inbox each morning.

Subscribe to this Blog via Email :