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);
评论加载中…
![]() |