关闭

Dom4j学习笔记

271人阅读 评论(0) 收藏 举报

下面的代码是在网上查找的,然后自己对照别人的在本地运行了一下,觉得很不错,所以就发布出来,版权不归本人

 

附件中有我运行的工程,可以直接测试

 

package hb.java;

import java.io.File;
import java.io.FileWriter;
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 Dom4jDemo {
	
	/*
	 * 建立一个xml文件,文件的名称由输入参数决定
	 * @param filename 需要建立的文件名
	 * @return 返回操作结果,0表示失败,1表示成功
	 */
	public int createXMLFile(String filename){
		
		int returnValue = 0;
		//创建一个Document对象,即根节点
		Document doc = DocumentHelper.createDocument();
		doc.addComment("comment 1");
		//在doc元素下面添加一个Element对象
		Element booksElement = doc.addElement("books");
		//在booksElement节点下面添加一个Element对象
		Element bookElement = booksElement.addElement("book");
		//给bookElement节点添加一个属性show=yes
		bookElement.addAttribute("show", "yes");
		//给bookElement对象下面添加一个Element对象
		Element titleElement = bookElement.addElement("title");
		//titleElement对象的文本节点的值为Dom4j Tutorials
		titleElement.setText("Dom4j Tutorials");
		
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "yes");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene Studing");
		
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "no");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene in action");
		booksElement.addComment("i am booksElement's commons");
		Element ownerElement = booksElement.addElement("owner");
		ownerElement.setText("huangbiao");
		
		try{
		//创建一个XMLWriter对象,封装了对Document写的操作
			XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));
			writer.write(doc);
			//关闭数据流
			writer.close();
			returnValue = 1;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return returnValue;
	}
	
	
	/*
	 * 修改xml文件中的内容,并另存为一个新文件
	 * @param filename修改对象文件
	 * @param newfilename 修改后另存为该文件
	 * @return 返回操作结果,0表示失败,1表示成功
	 */
	public int modifyXMLFile(String filename,String newfilename){
		int returnValue = 0;
		try {
			SAXReader saxReader = new SAXReader();
			Document doc = saxReader.read(new File(filename));
			//使用下面的方法一定要引用jaxen.jar包,否则页面会抛异常,查询book元素属性为show的结果集合
			List list = doc.selectNodes("/books/book/@show");
			Iterator it = list.iterator();
			while(it.hasNext()){
				Attribute attr = (Attribute)it.next();
				if(attr.getValue().equals("yes")){
					attr.setValue("no");
				}
			}
			
			/*
			 * 把owner项内容改为Tshinghua,并在owner节点中加入date节点,
				内容为2004-9-11,还为date节点添加一个参数type
			 */
			//查询books元素的子元素owner的节点
			list = doc.selectNodes("/books/owner");
			it = list.iterator();
			if(it.hasNext()){
				Element ownerElement = (Element)it.next();
				ownerElement.setText("Tshinghua");
				Element dateElement = ownerElement.addElement("date");
				dateElement.setText("2004-9-11");
				dateElement.addAttribute("type", "huangbiao");
			}
			
			/** 修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点 */
			list = doc.selectNodes("books/book");
			it = list.iterator();
			while(it.hasNext()){
				Element bookElement = (Element)it.next();
				Iterator iterator = bookElement.elementIterator("title");
				while(iterator.hasNext()){
					Element titleElement = (Element)iterator.next();
					if(titleElement.getText().equals("Dom4j Tutorials")){
						bookElement.remove(titleElement);
					}
				}
			}
			
			try{
				XMLWriter w = new XMLWriter(new FileWriter(new File(newfilename)));
				w.write(doc);
				w.close();
				returnValue = 1;
			}catch (Exception e) {
				// TODO: handle exception
			}
			
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnValue;
	}
	
	/*
	 * xml文件格式化的问题
	 */
	public int formatXMLFile(String filename){
		int returnValue = 0;
		try {
			SAXReader saxReader = new SAXReader();
			Document doc = saxReader.read(new File(filename));
			XMLWriter output = null;
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			output = new XMLWriter(new FileWriter(new File(filename)),format);
			output.write(doc);
			output.close();
			returnValue = 1;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnValue;
	}
	
}

 

 

package hb.java;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import org.dom4j.DocumentException;

import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Foo {

	public Document parse(File file) throws DocumentException {

		// 以DOM4J默认的SAX解析器解析

		SAXReader reader = new SAXReader();

		// read函数的形参可以是url 也可以是 File类型,也可以是STRING类型的相对或绝对路径

		Document document = reader.read(file);

		return document;

	}

	public void bar(Document document) throws DocumentException {

		// 获得根节点

		Element root = document.getRootElement();

		// i为根节点孩子节点的迭代器

		for (Iterator i = root.elementIterator(); i.hasNext();) {

			Element element = (Element) i.next();

			// do something

			System.out.println(element.getName());

		}

		// 名为“student1”节点以下孩子节点的迭代器

		for (Iterator i = root.elementIterator("student1"); i.hasNext();) {

			Element foo = (Element) i.next();

			// do something

			System.out.println(foo.getText());

		}

		// 根节点属性的迭代器

		for (Iterator i = root.attributeIterator(); i.hasNext();) {

			Attribute attribute = (Attribute) i.next();

			// do something

			System.out.println(attribute.getValue());

		}

	}
	
	public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );
 
        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
 
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "US" )
            .addText( "Bob McWhirter" );
 
        return document;
    }
	
	public void write(Document document) throws IOException {
		 
        // lets write to a file
        XMLWriter writer = new XMLWriter(
            new FileWriter( "output.xml" )
        );
        writer.write( document );
        writer.close();
 
        // 打印出Pretty的样式。即元素之间有换行。
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
 
        // 紧凑的格式,所有元素在一行
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    }

	public Document styleDocument(Document document, String stylesheet) throws Exception {

		// load the transformer using JAXP

		TransformerFactory factory = TransformerFactory.newInstance();

		Transformer transformer = factory.newTransformer(

				new StreamSource(stylesheet)

		);

		// now lets style the given document

		DocumentSource source = new DocumentSource(document);

		DocumentResult result = new DocumentResult();

		transformer.transform(source, result);

		// return the transformed document

		Document transformedDoc = result.getDocument();

		return transformedDoc;

	}


}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:310134次
    • 积分:8715
    • 等级:
    • 排名:第2262名
    • 原创:1096篇
    • 转载:14篇
    • 译文:0篇
    • 评论:5条
    最新评论