欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

dom4j读写xml

程序员文章站 2022-05-29 11:40:42
...
package com.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
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;

public class dom4j {
	public static void DOM4JCreateXML(){
		org.dom4j.Document document = DocumentHelper.createDocument();
		org.dom4j.Element bookstore = document.addElement("bookstore");
		org.dom4j.Element book = bookstore.addElement("book");
		book.addAttribute("id", "1");
		org.dom4j.Element name = book.addElement("name");
		name.setText("小王子");
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File("books4.xml");
		XMLWriter writer;
		try {
			writer = new XMLWriter(new FileOutputStream(file), format);
			writer.setEscapeText(false);
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void DOM4JreadXML() throws DocumentException{
		SAXReader sr=new SAXReader();
		Document Document = sr.read(new File("pom1.xml"));
		Element root=Document.getRootElement();
		Iterator it=root.elementIterator();
		while(it.hasNext()) {
			Element ele=(Element) it.next();
			List<Attribute> list=ele.attributes();
			for(Attribute attr:list) {
			System.out.println(attr.getName()+":"+attr.getValue());	
			}
		
			Iterator  suneles=ele.elementIterator();
			while(suneles.hasNext()) {
				Element ele1=(Element) suneles.next();
				
				System.out.println(ele1.getName()+":"+ele1.getStringValue());	
				}
			
			
		}	
	}
	public static void main(String[] args) throws DocumentException {
//		DOM4JreadXML();
		DOM4JCreateXML();
	}

}