Java & Xml tutorial (4) use DOM to generate XML files

Source: Internet
Author: User
The sub-component registration trigger event. after the parent component registration triggers the sub-component event, the method is written in the method. the parent component writes Doyoulikeme like this? {ChildWords} methods: {listenToMyBoy: function (somedata)

In the previous tutorial, we learned how to use DOM parsing to read and modify XML file content. today we will learn how to use DOM parsing to generate XML files.

The following are our specific requirements for the XML file to be generated:
1. the root node element is "Employees" and the namespace is "#". the root node contains a series of Employee elements.
2. Employee information is represented by the Employee node. the generated XML file contains information of two employees.
3. each employee has an "id" attribute.
4. the Employee element has four child elements: "name", "age", "role", and "gender ".
The following is the program code:

package com.journaldev.xml;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;public class XMLWriterDOM {    public static void main(String[] args) {        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();        DocumentBuilder dBuilder;        try {            dBuilder = dbFactory.newDocumentBuilder();            Document doc = dBuilder.newDocument();            //add elements to Document            Element rootElement =                doc.createElementNS("http://www.journaldev.com/employee", "Employees");            //append root element to document            doc.appendChild(rootElement);            //append first child element to root element            rootElement.appendChild(getEmployee(doc, "1", "Pankaj", "29", "Java Developer", "Male"));            //append second child            rootElement.appendChild(getEmployee(doc, "2", "Lisa", "35", "Manager", "Female"));            //for output to file, console            TransformerFactory transformerFactory = TransformerFactory.newInstance();            Transformer transformer = transformerFactory.newTransformer();            //for pretty print            transformer.setOutputProperty(OutputKeys.INDENT, "yes");            DOMSource source = new DOMSource(doc);            //write to console or file            StreamResult console = new StreamResult(System.out);            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));            //write data            transformer.transform(source, console);            transformer.transform(source, file);            System.out.println("DONE");        } catch (Exception e) {            e.printStackTrace();        }    }    private static Node getEmployee(Document doc, String id, String name, String age, String role,            String gender) {        Element employee = doc.createElement("Employee");        //set id attribute        employee.setAttribute("id", id);        //create name element        employee.appendChild(getEmployeeElements(doc, employee, "name", name));        //create age element        employee.appendChild(getEmployeeElements(doc, employee, "age", age));        //create role element        employee.appendChild(getEmployeeElements(doc, employee, "role", role));        //create gender element        employee.appendChild(getEmployeeElements(doc, employee, "gender", gender));        return employee;    }    //utility method to create text node    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {        Element node = doc.createElement(name);        node.appendChild(doc.createTextNode(value));        return node;    }}

Note that two StreamResult objects are created in the code. one is to output the content of the XML file to the console for debugging purposes, and the other is to write the XML content to the file.
XML content output by the program:

 
 
  
   Pankaj
  29
  
   Java Developer
  
  
   Male
  
  
   
    Lisa
   35
   
    Manager
   
   
    Female
   
  
 

The XML content is not formatted. if you need to format the XML content properly, refer to this article to format XML in Java.

In the previous tutorial, we learned how to use DOM parsing to read and modify XML file content. today we will learn how to use DOM parsing to generate XML files.
The following are our specific requirements for the XML file to be generated:
1. the root node element is "Employees" and the namespace is "#". the root node contains a series of Employee elements.
2. Employee information is represented by the Employee node. the generated XML file contains information of two employees.
3. each employee has an "id" attribute.
4. the Employee element has four child elements: "name", "age", "role", and "gender ".
The following is the program code:

package com.journaldev.xml;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;public class XMLWriterDOM {    public static void main(String[] args) {        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();        DocumentBuilder dBuilder;        try {            dBuilder = dbFactory.newDocumentBuilder();            Document doc = dBuilder.newDocument();            //add elements to Document            Element rootElement =                doc.createElementNS("http://www.journaldev.com/employee", "Employees");            //append root element to document            doc.appendChild(rootElement);            //append first child element to root element            rootElement.appendChild(getEmployee(doc, "1", "Pankaj", "29", "Java Developer", "Male"));            //append second child            rootElement.appendChild(getEmployee(doc, "2", "Lisa", "35", "Manager", "Female"));            //for output to file, console            TransformerFactory transformerFactory = TransformerFactory.newInstance();            Transformer transformer = transformerFactory.newTransformer();            //for pretty print            transformer.setOutputProperty(OutputKeys.INDENT, "yes");            DOMSource source = new DOMSource(doc);            //write to console or file            StreamResult console = new StreamResult(System.out);            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));            //write data            transformer.transform(source, console);            transformer.transform(source, file);            System.out.println("DONE");        } catch (Exception e) {            e.printStackTrace();        }    }    private static Node getEmployee(Document doc, String id, String name, String age, String role,            String gender) {        Element employee = doc.createElement("Employee");        //set id attribute        employee.setAttribute("id", id);        //create name element        employee.appendChild(getEmployeeElements(doc, employee, "name", name));        //create age element        employee.appendChild(getEmployeeElements(doc, employee, "age", age));        //create role element        employee.appendChild(getEmployeeElements(doc, employee, "role", role));        //create gender element        employee.appendChild(getEmployeeElements(doc, employee, "gender", gender));        return employee;    }    //utility method to create text node    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {        Element node = doc.createElement(name);        node.appendChild(doc.createTextNode(value));        return node;    }}

Note that two StreamResult objects are created in the code. one is to output the content of the XML file to the console for debugging purposes, and the other is to write the XML content to the file.
XML content output by the program:

 
 
  
   Pankaj
  29
  
   Java Developer
  
  
   Male
  
  
   
    Lisa
   35
   
    Manager
   
   
    Female
   
  
 

The above is the content of the Xml file generated by using DOM in Java & XML tutorial (4). For more information, see PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.