代码改变世界

用Jdom编写及解析xml文档

2012-07-23 22:09  Lves Li  阅读(155)  评论(0编辑  收藏  举报
package WildCat.Xml.JDom;

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

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

用Jdom编写xml文档:
1.
public class JdomTest1 {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//获得根节点
		Document document=new Document();
		//第一级元素
		Element root=new Element("学生花名册");
		//把元素加入到根节点上
		document.addContent(root);
		//二级元素
		Element student=new Element("学生");
		
		root.addContent(student);
		//注释
		Comment comment1=new Comment("计算机学院计113——1班"); 
		root.addContent(comment1);
		//属性
		Attribute num=new Attribute("学号","01"); 
		student.setAttribute(num);
		student.addContent(new Element("姓名").setText("WildCat")).addContent(new Element("性别").setText("男"));
		
		//设定输出格式
		Format format=Format.getPrettyFormat();	
		XMLOutputter out=new XMLOutputter(format);
	
		try {
			out.output(document, new FileOutputStream("JDOM.xml"));
			System.out.println("写入成功!");
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
	
			e.printStackTrace();
		}
		
		
	}

}
用Jdom解析xml:
package WildCat.Xml.JDom;

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

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class JDomTest2 {
	public static void main(String [] args) throws Exception
	{
	
	SAXBuilder bulider=new SAXBuilder();
	Document doc=bulider.build(new File("JDOM.xml"));
	//获得根节点
	Element root=doc.getRootElement();
	System.out.println(root.getName());
	//获得二级元素 学生
	Element student=root.getChild("学生");
	//获得属性
	List num=student.getAttributes();
	for(int i=0;i<num.size();i++)
	{
		Attribute attr=(Attribute)num.get(i);
		String attrName=attr.getName();
		String attrValue=attr.getValue();
		//输出
		System.out.println(attrName+"="+attrValue);
		
	}
	
	
	//获得三级元素 学生
	Element name=student.getChild("姓名");
	
	System.out.println(name.getName()+":"+name.getText());
	//删除元素
	student.removeChild("性别");
	//把删除后的文档放到JDOM2.xml中
	XMLOutputter out=new XMLOutputter(Format.getPrettyFormat());
	out.output(doc, new FileOutputStream("JDOM2.xml"));
	
	}
	
}