dom4j操作xml笔记

首先是读取xml文件。
SAXReader reader=new SAXReader();
Document doc=reader.read(new File(filepath));

这里的filepath为xml文件的路径。
获取了Document对象之后, 便可以对xml文件进行进一步的读取操作.


然后是写入文件

package com.lj.test;

import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Test06
{
	public static void main(String[] args) throws IOException
	{
		Document doc=DocumentHelper.createDocument();
		
		
		Element root=doc.addElement("users");
		Element user=root.addElement("user");
		user.addElement("id").addText("1");
		user.addElement("name").addText("z");
		
		
		user=root.addElement("user");
		user.addElement("id").addText("2");
		user.addElement("name").addText("w");
		
		
		
		 
		XMLWriter out=new XMLWriter(new FileWriter("src/main/resources/User.xml"),OutputFormat.createPrettyPrint());
		
		out.write(doc);
		
	
		
		
		out.flush();
		out.close();
	}
}



========================================
将list对象进行封装写入xml

package com.lj.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.lj.model.Person;

public class Test08
{
	public static void main(String[] args) throws IOException
	{	
		
		Document doc=DocumentHelper.createDocument();
		System.out.println(doc);
	 
		
		Person p1=new Person("li","233",25);
		Person p2=new Person("wu","123",27);
		
		List<Person> al=new ArrayList<Person>();
		al.add(p1);
		al.add(p2);
		
		
		doc=writeList2XML(doc, al);
		 
		XMLWriter writer=new XMLWriter(new FileWriter(new File("src/main/resources/Person.xml")),OutputFormat.createPrettyPrint());
		
		 
		
		writer.write(doc);
		
		writer.flush();
		writer.close();
	}

	private static Document writeList2XML(Document doc, List<Person> persons)
	{
		// Document doc=DocumentHelper.createDocument();
		Element root = doc.addElement("persons");
		System.out.println(root);

		for (Person p : persons)
		{

			Element ep = root.addElement("person");
			ep.addAttribute("age", p.getAge() + "");
			ep.addElement("name").setText(p.getName());
			ep.addElement("password").setText(p.getPassword());
			
		}
		
		
		
		 
		
		return doc;
		
		
	}
}

你可能感兴趣的:(xml)