2006-08-22

用DOM/JDOM解析XML文件(3)

来源: CSDN 作者:Javer.Leo 评论 0 条
  以前记录过两个自己写的读写XML文件的帖子,感觉很不完善,只适合简单的应用,无法完成更复杂高级的功能。最近正好用到一个更优雅的,再记录下来,以备以后查阅。
  越来越喜欢用“优雅”这个词来形容一段好的代码,没有什么好的理由,就是感觉挺好。喜欢一个词需要理由吗?喜欢一个东西需要理由吗?喜欢一个人需要理由吗?……

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

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

/**
* Jdom解析XML
*
* @FileName:XMLUtil.java
* @author Javer.Leo (QQ:84831612)
* @date 2006-8-16
*/
public final class XMLUtil
{
/**
* 定义xml编码方式
*/
public static final String ENCODE_GBK = "GBK";
public static final String ENCODE_UTF8 = "UTF-8";
public static final String ENCODE_UTF16 = "UTF-16";
public static final String ENCODE_GB2312 = "gb2312";
public static final String ENCODE_ISO8859 = "ISO8859-1";

private static Format format = Format.getPrettyFormat();

static {
format.setEncoding(ENCODE_UTF8);
}

/**
* Read and parse an xml document from the file at xml/sample.xml.
* This method corresponds to the code in Listing 7.
* @param filePath 要解析的xml文件路径
* @return the JDOM document parsed from the file.
* @throws IOException
*/
public static Document readDocument(String filePath) throws IOException {
try {
SAXBuilder builder = new SAXBuilder(false);
Document anotherDocument = builder.build(new File(filePath));
return anotherDocument;
} catch(Exception e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}

/**
* Read and parse an xml document from the file at xml/sample.xml.
* This method corresponds to the code in Listing 7.
* @param filePath 要解析的xml文件路径
* @return the JDOM document parsed from the file.
* @throws IOException
*/
public static Document readDocument(InputStream input) throws IOException {
try {
SAXBuilder builder = new SAXBuilder(false);
Document anotherDocument = builder.build(input);
input.close();
return anotherDocument;
} catch(Exception e) {
throw new IOException(e.getMessage());
}
}

/**
* 读取xml文件
* @param srcFile 目标文件
* @return DOM对象
* @throws IOException
*/
public static Document readDocument(File srcFile) throws IOException {
try {
SAXBuilder builder = new SAXBuilder();
Document anotherDocument = builder.build(srcFile);
共5页: 上一页 1 [2] [3] [4] [5] 下一页

(本文仅表明作者个人观点,不代表本站及其管理员立场.) 推荐 收藏 投稿 打印 返回 关闭
上一篇:MYSQL,Oracle,SQL数据库在JSP中的驱动  
下一篇:用XMLHTTP组件解析图片地址并保存
    评论加载中…
 推荐文章
     

网站首页  -  网站地图 -   站长论坛  -  网站投稿  -    -  网站管理
Copyright © 2008 芜湖站长站 All Rights Reserved 皖ICP备07500611号