免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 891 | 回复: 0
打印 上一主题 下一主题

java对xml文件的操作 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-06-06 09:51 |只看该作者 |倒序浏览

java对xml文件的操作。这个太长了,转的。
文档对象模型 (DOM) 是一个文档标准,对于完备的文档和复杂的应用程序,DOM 提供了大量灵活性。DOM标准是标准的。它很强壮且完整,并且有许多实现。这是许多大型安装的决定因素--特别是对产品应用程序,以避免在API发生改变时进行大量的改写。
以上是我在选择处理XML数据时之所以没有选择JDOM或者dom4j等其它面向对象的标准的原因,不过也由于DOM从一开始就是一种与语言无关的模型,而且它更趋向用于像C或Perl这类语言,没有利用Java的面向对象的性能,所以在使用的过程中也遇到了不少的麻烦,今天这里做一个小结。另外,我目前使用XML主要是作为数据传输的统一格式,并统一用户界面展示的接口,应用的面并不是很广,所以使用到的DOM的内容其实不多。
在准备使用它的时候,是做了充足的准备的,也有遇到困难的准备,所以一开始就有了一个简单的工具类来封装DOM对象使用时必要的公共方法,实际证明这样做是很明智的,一个简单的创建Document对象的操作,要是每次都需要写上5行以上代码,并且还要处理那些烦人的Exception,实在是会打击大家的积极性,所以在最初,做了一个XMLTool类,专门封装了如下的公共方法:
1、 Document对象创建(包括空的Document对象创建,以一个给定Node节点作为根节点创建。
2、 将一个规范的XML字符串转换成一个Document对象。
3、 从物理硬盘读取一个XML文件并返回一个Document对象。
4、 将一个Node对象转换成字符串。
其中每个方法都截获相关的DOM操作所抛出的异常,转换成一个RuntimeException抛出,这些异常在实际使用过程中,一般状况下其实都不会抛出,特别是象生成一个Document对象时的ParserConfigurationException、转换Node节点成字符串时要生成一个Transformer对象时的TransformerConfigurationException等等,没有必要在它们身上花时间精力。而且真就出了相关的异常的话,其实根本没有办法处理,这样的状况通常是系统环境配置有问题(比如必要的DOM实现解析器等包没有加入环境),所以包装该异常时只是很简要的获取其Message抛出。
代码如下:
/**
* 初始化一个空Document对象返回。
* @return a Document
*/
public static Document newXMLDocument() {
try {
return newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 初始化一个DocumentBuilder
* @return a DocumentBuilder
* @throws ParserConfigurationException
*/
public static DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException {
return newDocumentBuilderFactory().newDocumentBuilder();
}
/**
* 初始化一个DocumentBuilderFactory
* @return a DocumentBuilderFactory
*/
public static DocumentBuilderFactory newDocumentBuilderFactory() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
return dbf;
}
/**
* 将传入的一个XML String转换成一个org.w3c.dom.Document对象返回。
* @param xmlString 一个符合XML规范的字符串表达。
* @return a Document
*/
public static Document parseXMLDocument(String xmlString) {
if (xmlString == null) {
throw new IllegalArgumentException();
}
try {
return newDocumentBuilder().parse(
new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 给定一个输入流,解析为一个org.w3c.dom.Document对象返回。
* @param input
* @return a org.w3c.dom.Document
*/
public static Document parseXMLDocument(InputStream input) {
if (input == null) {
throw new IllegalArgumentException("参数为null!");
}
try {
return newDocumentBuilder().parse(input);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 给定一个文件名,获取该文件并解析为一个org.w3c.dom.Document对象返回。
* @param fileName 待解析文件的文件名
* @return a org.w3c.dom.Document
*/
public static Document loadXMLDocumentFromFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("未指定文件名及其物理路径!");
}
try {
return newDocumentBuilder().parse(new File(fileName));
} catch (SAXException e) {
throw new IllegalArgumentException(
"目标文件(" + fileName + ")不能被正确解析为XML!\n" + e.getMessage());
} catch (IOException e) {
throw new IllegalArgumentException(
"不能获取目标文件(" + fileName + ")!\n" + e.getMessage());
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 给定一个节点,将该节点加入新构造的Document中。
* @param node a Document node
* @return a new Document
*/
public static Document newXMLDocument(Node node) {
Document doc = newXMLDocument();
doc.appendChild(doc.importNode(node, true));
return doc;
}
/**
* 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。
* @param node DOM Node 对象。
* @return a XML String from node
*/
public static String toString(Node node) {
if (node == null) {
throw new IllegalArgumentException();
}
Transformer transformer = newTransformer();
if (transformer != null) {
try {
StringWriter sw = new StringWriter();
transformer.transform(
new DOMSource(node),
new StreamResult(sw));
return sw.toString();
} catch (TransformerException te) {
throw new RuntimeException(te.getMessage());
}
}
return errXMLString("不能生成XML信息!");
}
/**
* 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。
* @param node DOM Node 对象。
* @return a XML String from node
*/
public static String toString(Node node) {
if (node == null) {
throw new IllegalArgumentException();
}
Transformer transformer = newTransformer();
if (transformer != null) {
try {
StringWriter sw = new StringWriter();
transformer.transform(
new DOMSource(node),
new StreamResult(sw));
return sw.toString();
} catch (TransformerException te) {
throw new RuntimeException(te.getMessage());
}
}
return errXMLString("不能生成XML信息!");
}
/**
* 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。
* @return a Transformer encoding gb2312
*/
public static Transformer newTransformer() {
try {
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "gb2312");
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.VERSION, "1.0");
properties.setProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperties(properties);
return transformer;
} catch (TransformerConfigurationException tce) {
throw new RuntimeException(tce.getMessage());
}
}
/**
* 返回一段XML表述的错误信息。提示信息的TITLE为:系统错误。之所以使用字符串拼装,主要是这样做一般
* 不会有异常出现。
* @param errMsg 提示错误信息
* @return a XML String show err msg
*/
public static String errXMLString(String errMsg) {
StringBuffer msg = new StringBuffer(100);
msg.append("");
msg.append("");
return msg.toString();
}
/**
* 返回一段XML表述的错误信息。提示信息的TITLE为:系统错误
* @param errMsg 提示错误信息
* @param errClass 抛出该错误的类,用于提取错误来源信息。
* @return a XML String show err msg
*/
public static String errXMLString(String errMsg, Class errClass) {
StringBuffer msg = new StringBuffer(100);
msg.append("");
msg.append(
"");
return msg.toString();
}
/**
* 返回一段XML表述的错误信息。
* @param title 提示的title
* @param errMsg 提示错误信息
* @param errClass 抛出该错误的类,用于提取错误来源信息。
* @return a XML String show err msg
*/
public static String errXMLString(
String title,
String errMsg,
Class errClass) {
StringBuffer msg = new StringBuffer(100);
msg.append("");
msg.append(
"");
return msg.toString();
}
以上都是DOM的基本应用,所以就不一一详细说明了。
在实际使用过程中,有几种状况使用很频繁,但是DOM的接口的设计却使该操作很麻烦,所以分别添加了相应的处理方法。
其中最麻烦的要数获取一个节点的Text子节点文本信息了,如下的XML节点:

text

在拥有element节点对象时,要获取其中的文本信息"text",首先要获取element节点的子节点列表,要判断其是否存在子节点,如果存在,那么遍历其子节点找到一个TextNode节点,通过getNodeValue()方法来获取该文本信息,由于这里element节点没有信息时没有子节点,所以必须判断element节点是否存在子节点才能去访问真正包含了文本信息的TextNode节点,那么如果要处理的数据都是以这种形式给出的,就会增加大量的开发代码同时让开发工作枯燥无味,因此这里使用了一个默认的约定实现,就是,给出了一个公共方法,该方法取给定Node下的直接子节点的Text节点文本信息,如果不存在Text节点则返回null,这个约定虽然使该方法的使用有所限制,也可能导致错误使用该方法,但是,按实际使用的状况来看,这样的约定和使用方式是没有问题的,因为实际用到的都是上面举的例子的状况,代码:
/**
* 这个方法获取给定Node下的Text节点文本信息,如果不存在Text节点则返回null。
* 注意:是直接子节点,相差2层或2层以上不会被考虑。
* @param node a Node 一个Node。
* @return a String 如果给定节点存在Text子节点,则返回第一个访问到的Text子节点文本信息,如果不存在则返回null。
*/
public static String getNodeValue(Node node) {
if (node == null) {
return null;
}
Text text = getTextNode(node);
if (text != null) {
return text.getNodeValue();
}
return null;
}
/**
* 这个方法获取给定Node下的Text节点,如果不存在Text节点则返回null。
* 注意:是直接子节点,相差2层或2层以上不会被考虑。
* @param node a Node 一个Node。
* @return a Text 如果给定节点存在Text子节点,则返回第一个访问到的Text子节点,如果不存在则返回null。
*/
public static Text getTextNode(Node node) {
if (node == null) {
return null;
}
if (node.hasChildNodes()) {
NodeList list = node.getChildNodes();
for (int i = 0; i

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/32854/showart_315692.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP