XML文件操作(三)

  • JDOM解析操作

使用Java语言编写的、用于读写操作XML的一套组件,jar包下载地址:http://www.jdom.org/downloads/index.html

既可以快速读取也可以修改文件

主要操作类:DocumentDOMBuilder用来建立一个JDOM树、ElementAttribute元素中属性、XMLOutputter将JDOM结构树格式化为一个XML文件,并且以输出流的方式加以输出

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
import org.junit.Ignore;
import org.junit.Test;


public class JdomTest {
	
	@Test
	@Ignore
	public void testWrite() {
		
		Element books=new Element("books");//定义根节点
		Element book=new Element("book");
		Element name=new Element("name");
		Element author=new Element("author");
		Element an=new Element("name");
		Element ab=new Element("birthyear");
		Attribute id=new Attribute("id", "test");
		
		Document doc=new Document(books);//Document对象放入根节点
		
		name.setText("测试书名");//设置文本内容,添加元素属性
		name.setAttribute(id);
		
		an.setText("测试作者名");
		ab.setText("测试作者年");
		
		author.addContent(an);//设置各元素节点之间的关系
		author.addContent(ab);
		
		book.addContent(name);
		book.addContent(author);
		
		books.addContent(book);
		
		XMLOutputter out=new XMLOutputter();//用来输出XML文件
		out.setFormat(out.getFormat().setEncoding("utf-8"));//设置编码格式
		try {
			out.output(doc, new FileOutputStream("write.xml") );
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Test
	public void testRead() throws Exception {
		SAXBuilder builder=new SAXBuilder();//建立SAX解析
		Document read_doc=builder.build("write.xml");//找到Document
		
		Element books=read_doc.getRootElement();//找到根元素
		List<?> list=books.getChildren("book");
		for (int i = 0; i < list.size(); i++) {
			Element e=(Element) list.get(i);//取出book集合的一个子集	
			String name=e.getChildText("name");//取出book下的name元素	
			String id=e.getChild("name").getAttribute("id").getValue();//取出name元素的属性id的值
			System.out.println(name+":"+id);
			List<?> author=e.getChild("author").getChildren();
			for (int j = 0; j < author.size(); j++) {
				Element ae=(Element) author.get(j);
				String value=ae.getText();
				System.out.println(ae.getName()+":"+value);
			}
		}
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/qq_37575994/article/details/100079623
今日推荐