XML summary -- XML parsing

Article directory

XML analysis

1, XML parsing

  • There are two ways to parse XML: dom and sax
    • dom:(Document Object Model), a way to process XML
    • sax:(Simple API for XML) is not an official standard, but it is a de facto standard in the XML community that almost all XML parsers support.
  • XML parsing development package
    • Jaxp,Jdom,dom4j

1. DOM parsing

DOM model

When parsing XMl documents, DOM parsers will parse all elements in documents into Node objects (nodes) according to their hierarchical relationships.

Advantages: Xml files are built into tree structure in memory, and nodes can be traversed and modified

Disadvantages: if the file is large, the memory is under pressure, and the actual parsing time is long

DOM programming steps

  • Call the DocumentBuilderFactory.newInstance() method to get the factory that creates the DOM parser.

  • Call the newDocumentBuilder method of the factory object to get the DOM parser object.

  • Call the parse() method of the DOM parser object to parse the XML Document and get the Document object representing the entire Document. Then you can use the DOM feature to operate the entire XML Document.


<?xml version="1.0" encoding="UTF-8"?>
	<employee id="0">
	<employee id="1">
		<name height="178">Edward</name>
	<employee id="2">
	<employee id="3">


import javax.xml.parsers.*;

import org.w3c.dom.*;

 * Dom Parsing XML
 * @author USE
public class DOMXml {
	public static void main(String[] args) throws Exception {
		//Get the factory to create the DOM parser
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		//Set the parser generated by this factory, ignoring comments
		//Ignore spaces
		//Call the method of the factory object to get the DOM parser object
		DocumentBuilder builder = dbf.newDocumentBuilder();
		//Call DOM parser object to parse XML Document and get Document
		Document doc = (Document) builder.parse("src/com/MyXml.xml");
		//Get root node
		Element root = doc.getDocumentElement();
		//Get node by tag name
		NodeList nodeList = doc.getElementsByTagName("employee");
		System.out.println("employess Number of nodes:"+nodeList.getLength());
		//Traverse nodeList
		for(int i=0;i<nodeList.getLength();i++){
			Element element = (Element)nodeList.item(i);
			//Get id attribute value
			String attribute = element.getAttribute("id");
			System.out.println("id:" + attribute);
			//Get the first employee
				//Get the name text below the element
				System.out.println("name Text value:" + element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
				//Get the sex text below the element
				System.out.println("sex Text value:" + element.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue());
				//Get the age text below the element
				System.out.println("age Text value:" + element.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
				//Get the text value of the first weight
				System.out.println("weight Text value:" + element.getElementsByTagName("weight").item(0).getFirstChild().getNodeValue());
				//Get the text value of a tag in the second weight
				System.out.println("weight Of a Text value:" + element.getElementsByTagName("weight").item(1).getFirstChild().getFirstChild().getNodeValue());

2. SAX parsing

SAX analysis

When using DOM to parse XML documents, you need to read the entire XML document, and in memory, you need to construct the document object representing the entire DOM tree, so as to operate on the XML document; SAX parsing allows you to ignore the document when reading the document, rather than wait until the entire document is loaded before processing the document

Advantages: analysis can start immediately, fast, no memory pressure

Disadvantage: the node cannot be modified

SAX programming steps

  • Create SAX resolution factory with SAXParserFactory
    • SAXParerFactory spf = SAXParerFactory.newInstance();
  • Get parser object through SAX parsing factory
    • SAXParser sp = spf.newSAXParser();
  • Get an XML reader from the parser object
    • XMLReader xmlReader = sp.getXMLReader();
  • Set event handler for reader
    • xmlReader.setContentHandler(new BookParserHandler());
  • Parsing xml files
    • xmlReader.parse("book.xml");


import java.io.File;
import javax.xml.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
 - @author USE
public class SAXXml extends DefaultHandler{
	//Called at the beginning of parsing the entire document
	public void startDocument() throws SAXException {
		System.out.println("Start document");
	//Called at the end of parsing the entire document
	public void endDocument() throws SAXException {
		System.out.println("End document");
	//Called at the beginning of parsing an element
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		System.out.println("Start parsing element:" + qName);
	public static void main(String[] args) throws Exception{
		//Create a sax parsing factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		//Create parser name
		SAXParser saxParser = spf.newSAXParser();
		//Creating a File indicates the xml to parse
		File file = new File("src/com/MyXml.xml");
		//Parsing XML files
		saxParser.parse(file, new SAXXml());

3. Dom4j parsing xml

Dom4j analysis

  • Dom4j is a simple and flexible open source library. Dom4j was separated and developed independently by early developers of JDOM. Unlike JDOM, Dom4j uses interfaces and abstract classes. Although the API of Dom4j is relatively complex, it provides better flexibility than JDOM.
  • Dom4j is a very excellent Java XML API, with excellent performance, powerful functions and easy to use features. Now many software uses Dom4j.
  • To develop with Dom4j, you need to download the corresponding jar file of Dom4j.

Dom4j programming query add nodes and attributes
dom4j-1.6.1.jar; jaxen-1.1-beta-8.jar; jdom-1.0.jar package are required

Code example:

<?xml version="1.0" encoding="UTF-8"?>
	<emp id="0">
		<name>Zhang San</name>
	<emp id="1">
		<name>Wang Wu</name>
	<emp id="2">
		<name>Zhao Liu</name>
	<emp id="3">
		<name>Xiao Ming</name>

Emp.java (object encapsulation class)

public class Emp {
	private int id;
	private String name;
	private int age;
	private String gender;
	private double salary;
	 * Construction method
	public Emp() {
		// TODO Auto-generated constructor stub
	public Emp(int id, String name, int age, String gender, double salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.salary = salary;

	 * get/set Method
	 * @return
	public int getId() {
		return id;

	public void setId(int id) {
		this.id = id;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public int getAge() {
		return age;

	public void setAge(int age) {
		this.age = age;

	public String getGender() {
		return gender;

	public void setGender(String gender) {
		this.gender = gender;

	public double getSalary() {
		return salary;

	public void setSalary(double salary) {
		this.salary = salary;
	 * toString Method
	public String toString() {
		return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", salary=" + salary + "]";


import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import com.entity.Emp;

public class TestDomFJ {
	public static void main(String[] args) throws Exception {
		//Create SAXReader parser
		SAXReader reader = new SAXReader();
		//Indicate the parsed file, parse the file, and get the document document
		Document doc = reader.read(new File("src/com/EmpList.xml"));
		//Get root node
		Element root = doc.getRootElement();
		//Get all child nodes under the root node
		List<Element> elements = root.elements();
		//Create list < EMP > save all employee objects
		List<Emp> list = new ArrayList<Emp>();
		//Traverse child nodes
		for(Element element : elements){
			//Get the properties of a node
			String id = element.attribute("id").getValue();
			//Get node and node value
			String name = element.element("name").getText();
			String age = element.elementText("age");
			String gender = element.elementText("gender");
			String salary = element.elementText("salary");
			Emp emp = new Emp(Integer.parseInt(id),name,Integer.parseInt(age),gender,Double.parseDouble(salary));
		//Output list
	 * Create document, add node
	 * Add child node, addElement()
	 * Add text value, addText()
	 * Add child nodes and set text, addElement().addText()
	 * Add attribute, use addAttribute(,)
	 * @throws Exception
	public void testAdd() throws Exception{
		//list store Emp objects
		List<Emp> emps = new ArrayList<Emp>();
		emps.add(new Emp(1,"Zhang San",33,"male",9000.0));
		emps.add(new Emp(2,"Li Si",25,"male",5000.0));
		emps.add(new Emp(3,"Wang Wu",20,"male",4000.0));
		//Create a document object
		Document doc = DocumentHelper.createDocument();
		//Create root node
		Element root = doc.addElement("list");
		for(Emp emp : emps){
			//Add a child element named emp to the root element
			Element ele = root.addElement("emp");
			//Add id attribute for emp element
			ele.addAttribute("id", emp.getId()+"");
			//Add child nodes and set text values in nodes
		//Generating physical files with XMLWriter
		//Create output stream, execute output path
		FileOutputStream fos = new FileOutputStream("src/com/EmpList1.xml");
		XMLWriter writer = new XMLWriter();
		//Write out the document to the specified path
		//Closed flow

dom4j programming - delete modified nodes and attributes


	 * Delete node
	 * @throws Exception
	public void testRemove() throws Exception{
		//Using SAXReader to read documents
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read("src/com/EmpList.xml");
		//Get root node
		Element root = doc.getRootElement();
		Element element = (Element) root.elements().get(1);
		//Delete attribute for node
		Element name = element.element("name");
		//Delete name node
	 * modify
	 * @throws Exception
	public void testUpdate() throws Exception{
		SAXReader sax = new SAXReader();
		Document doc = sax.read("src/com/EmpList1.xml");
		//Get heel node
		Element root = doc.getRootElement();
		Element e2 = (Element)root.elements().get(1);
		Attribute id = e2.attribute("id");
		//Modify id attribute value
		//Get name node
		Element name = e2.element("name");
		//Modify the text value of name
		name.setText("Zhang Quan Chen");
Published 18 original articles, won praise 7, visited 286
Private letter follow

Tags: xml Attribute Java Programming

Posted on Thu, 16 Jan 2020 08:03:00 -0500 by stovellp