XML Programming-DOM4J

黄舟
Release: 2017-02-20 15:13:52
Original
1333 people have browsed it

XMLProgramming-DOM4J

##Basic Overview


dom4j

is a JavaXML API , similar to jdom, used to read and write XML files. dom4j is a very excellent JavaXML API, which has the characteristics of excellent performance, powerful functions and extremely easy to use. It is also a Open source software, you can find it at SourceForge. You can also find an article on IBM developerWorks on the performance, functionality and ease of use of the mainstream Java XML API reviews, so you can know that dom4j is excellent in every aspect. Nowadays you can see that more and more Java software are using dom4j to read and write XML, it is particularly worth mentioning that even Sun#JAXM is also using dom4j . This is already a must-use jar package, Hibernate also uses it to read and write configuration files.

PSDOM4JOne of the reasons why it is so powerful is that it supports XPath Technology, DOM4J also has corresponding reference documents, you can search and download them if you need them.

Why is there

DOM4J?

Before, the two technologies described in the blog,

DOM and SAX technology, the disadvantage of the former is that it is time consuming Memory, the disadvantage of the latter is that it can only perform read operations, while DOM4J can both submit efficiency and perform crud operations .

PS: To use DOM4J, you need to import the corresponding basic JAR package, If you use the extension function of DOM4J, you also need to import the extension JAR package.

DOM4JGetting started

DOM4JThree ways to obtain Document objects

1.ReadXMLfile,obtaindocumentobject(commonly used)

    SAXReader reader = new SAXReader();
    Document   document = reader.read(new File(“src/input.xml"));
Copy after login

2.Parse the text in the form of XML, and get the document Object

    String text = "<members></members>";
    Document document = DocumentHelper.parseText(text);
Copy after login

3.Active creationdocumentObject

    Document document = DocumentHelper.createDocument();
    //创建根节点
    Element root = document.addElement("members");
Copy after login

PS: Be careful to import the corresponding JAR package.



Node object

1, get the root node of the document

    Element root = document.getRootElement();
Copy after login



2, get the child nodes of a node



    Element element=node.element(“书名");
Copy after login

3, get the content of the node

    String text1=node.getText();
    String text2=node.getTextTrim();	// 去掉内容前面和后面的空格
Copy after login

4, get all the names under a node named "member" child nodes, and traverse

    List nodes = rootElm.elements("member");
    for (Iterator it = nodes.iterator(); it.hasNext();) {
          Element elm = (Element) it.next();
          // do something
    }
Copy after login

5, traverse all child nodes under a certain node

    for(Iterator it=root.elementIterator();it.hasNext();){
        Element element = (Element) it.next();
           // do something
      }
Copy after login

6, add sub-node under a node

    Element ageElm = newMemberElm.addElement("age");
Copy after login

7, set node text

    element.setText("29");
Copy after login

8, delete A certain node

    //childElm是待删除的节点,parentElm是其父节点
    parentElm.remove(childElm);
Copy after login

9, add a CDATA node

    Element contentElm = infoElm.addElement("content");
    contentElm.addCDATA(diary.getContent());
Copy after login


PS: Note that nodes cannot be accessed across layers.


Node object attributes

1, get an attribute under a certain node

    Element root=document.getRootElement();    
      //属性名name
    Attribute attribute=root.attribute("size");
Copy after login

2, get the text of the attribute

     String text=attribute.getText();
Copy after login

3, delete an attribute

    Attribute attribute=root.attribute("size");
    root.remove(attribute);
Copy after login

4, traverse all attributes of a node

     Element root=document.getRootElement();    
    for(Iterator it=root.attributeIterator();it.hasNext();){
           Attribute attribute = (Attribute) it.next();
           String text=attribute.getText();
            System.out.println(text);
     }
Copy after login

5, Set the attributes and text of a node

    newMemberElm.addAttribute("name", "sitinspring");
Copy after login

6, Set the text of the attribute

    Attribute attribute=root.attribute("name");
     attribute.setText("sitinspring");
Copy after login


Insert a node at the specified position

1.Get the node list at the insertion position (list)

2.Call list.add(index,elemnent), determined by index## The insertion position of #element.

Element

Elements can be obtained through the DocumentHelper object. Sample code:

    Element aaa = DocumentHelper.createElement("aaa");
    aaa.setText("aaa");
    List list = root.element("书").elements();
    list.add(1, aaa);
    //更新document
Copy after login


Write document to

XML file


1

, If the document is in English


XMLWriter writer = new XMLWriter(new  FileWriter("output.xml"));
writer.write(document);
writer.close();
Copy after login

2、如果文档含有中文

OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("utf-8");

XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/pc/XML8.xml"), outputFormat);
xmlWriter.write(document);
xmlWriter.close();
Copy after login

PS:出现乱码的原因是因为输出字符集不能识别中文,这样可以通过OutputFormatsetEncoding方法设置为UTF-8,然后再使用XMLWriter这种形参的(OutputStream out, OutputFormat format) 构造方构造方法,就能解决乱码问题了,至于为什么会用createPrettyPrint方法,是因为这样做输出的格式更符合人的阅读习惯。


综合案例

XML8.xml

<?xml version="1.0" encoding="utf-8"?>
<班级 班次="1班" 编号="C1">
	<学生 学号="n1" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>张三</名字>
		<年龄>20</年龄>
		<介绍>不错</介绍>
	</学生>
	<学生 学号="n2" 性别="女" 授课方式="面授" 朋友="n1 n3" 班级编号="C1">
		<名字>李四</名字>
		<年龄>18</年龄>
		<介绍>很好</介绍>
	</学生>
	<学生 学号="n3" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>王五</名字>
		<年龄>22</年龄>
		<介绍>非常好</介绍>
	</学生>
	<学生 性别="男" 班级编号="C1">
		<名字>小明</名字>
		<年龄>30</年龄>
		<介绍>好</介绍>
	</学生>
</班级>
Copy after login


package com.pc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
 * 
 * @author Switch
 * @function 使用DOM4j解析XML文件
 * 
 */
public class XML8 {
	// 使用DOM4j对XML进行CRUD操作
	public static void main(String[] args) throws Exception {
		// 1.得到解析器
		SAXReader saxReader = new SAXReader();
		// 2.指定解析哪个XML文件
		Document document = saxReader.read(new File("src/com/pc/XML8.xml"));
		// list(document.getRootElement());
		// read(document);
		// readByXPath(document);
		// add(document);
		// delete(document);
		// updateElement(document);
		// updateAttribute(document);
		// addByIndex(document, 3);
	}

	// 更新属性(修改所有班级编号为C2)
	public static void updateAttribute(Document document) throws Exception {
		// 得到所有学生
		List<Element> students = document.getRootElement().elements("学生");
		for (Element e : students) {
			// 修改班级编号
			e.addAttribute("班级编号", "C2");
		}
		updateToXML(document);
	}

	// 更新元素(将所有学生的年龄+3)
	public static void updateElement(Document document) throws Exception {
		// 得到所有学生
		List<Element> students = document.getRootElement().elements("学生");
		for (Element e : students) {
			// 取出年龄
			Element age = e.element("年龄");
			age.setText(Integer.parseInt(age.getTextTrim()) + 3 + "");
		}
		updateToXML(document);
	}

	// 删除元素(删除第一个学生)
	public static void delete(Document document) throws Exception {
		// 找到元素
		Element stu = document.getRootElement().element("学生");
		// 删除
		stu.getParent().remove(stu);

		// 更新
		updateToXML(document);
	}

	// 添加元素到指定位置
	public static void addByIndex(Document document, int index)
			throws Exception {
		// 创建一个元素
		Element newStu = DocumentHelper.createElement("学生");
		newStu.setText("小花");
		// 得到所有学生的list
		List<Element> students = document.getRootElement().elements("学生");
		// 按索引添加
		students.add(index, newStu);

		// 更新
		updateToXML(document);
	}

	// 添加元素(添加一个学生到xml中)
	public static void add(Document document) throws Exception {
		// 创建一个学生节点对象

		Element newStu = DocumentHelper.createElement("学生");
		// 给元素添加属性
		newStu.addAttribute("学号", "n4");
		Element newStuName = DocumentHelper.createElement("名字");
		Element newStuAge = DocumentHelper.createElement("年龄");
		Element newStuIntro = DocumentHelper.createElement("介绍");

		// 把子元素挂载到学生节点下
		newStu.add(newStuName);
		newStu.add(newStuAge);
		newStu.add(newStuIntro);
		// 将学生挂载在根节点下
		document.getRootElement().add(newStu);

		// 更新
		updateToXML(document);
	}

	private static void updateToXML(Document document)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		// 更新xml文件
		// 直接输出会出现中文乱码
		OutputFormat outputFormat = OutputFormat.createPrettyPrint();
		outputFormat.setEncoding("utf-8");

		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(
				"src/com/pc/XML8.xml"), outputFormat);
		xmlWriter.write(document);
		xmlWriter.close();
	}

	// xpath技术,跨层读取某个元素
	public static void readByXPath(Document document) throws Exception {
		// 取出第一个学生
		Element student = (Element) document.selectSingleNode("/班级/学生[1]");
		System.out.println("姓名:" + student.elementText("名字") + "\t年龄:"
				+ student.elementText("年龄") + "\t介绍:"
				+ student.elementText("介绍") + "\t性别:"
				+ student.attributeValue("性别"));
	}

	// 读取指定的某个元素(读取第一个学生的信息)
	public static void read(Document document) throws Exception {
		// 得到根元素
		Element root = document.getRootElement();
		// root.elements("学生"); 取出root元素下的所有学生元素
		// root.element("学生"); 取出root元素下的第一个学生元素
		// 取出root元素下的第一个学生元素
		Element student = (Element) root.elements("学生").get(0);
		System.out.println("姓名:" + student.elementText("名字") + "\t年龄:"
				+ student.elementText("年龄") + "\t介绍:"
				+ student.elementText("介绍") + "\t性别:"
				+ student.attributeValue("性别"));
	}

	// 遍历xml文件
	public static void list(Element element) {
		System.out.println("元素名称:" + element.getName() + "\t元素内容:"
				+ element.getTextTrim());

		Iterator<Element> iterator = element.elementIterator();

		while (iterator.hasNext()) {
			Element e = iterator.next();
			// 递归
			list(e);
		}
	}
}
Copy after login

 以上就是XML编程-DOM4J的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template