您的位置:首页 > 编程语言 > Java开发

java 操作xml数据 转换byte spring源码分享

2011-07-27 11:28 756 查看
所涉及的jar包位于 jre/lib/rt.jar
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;

InputSource功能:
此类允许 SAX 应用程序封装有关单个对象中的输入源的信息,它可包括公共标识符、系统标识符、字节流(可能带有指定的编码)、基本 URI 和/ 或字符流。
在以下两种情况下应用程序可以将输入源提供给解析器:作为 Parser.parse 方法的参数,或者作为 EntityResolver.resolveEntity 方法的返回值。
SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入。如果有字符流可用,则解析器将直接读取该流,而忽略该流中找到的任何文本编码声明。如果没有字符流,但却有字节流,则解析器将使用该字节流,从而使用在 InputSource 中指定的编码,或者另外(如果未指定编码)通过使用某种诸如 XML 规范 中的算法算法自动探测字符编码。如果既没有字符流,又没有字节流可用,则解析器将尝试打开到由系统标识符标识的资源的 URI 连接。
InputSource 对象属于该应用程序:SAX 解析器将不会以任何方式修改它(它可以在必要时修改副本)。但是,作为解析终止清除的一部分,对字节流和字符流的标准处理就是关闭这二者,因此在将此类流传递给解析器后应用程序不应尝试重新使用它们。

spring源码中:org.springframework.beans.factory.xml.DefaultDocumentLoader
实现了对Document、DocumentBuilderFactory、DocumentBuilder创建方式

1、创建xml文件的方式:
.获取Document对象->创建Element跟元素( doc.createElement(“”));->将根元素添加到Document对象中-》通过Element的setAttribute方法设置属性值(如果有子节点,还是
通过doc.createElement创建子根元素,然后把子根元素放到根元素中
代码示例:
Document doc = domBuilder.newDocument() ;
Element ctmlEntry = doc.createElement(XMLTAG_CTML) ;
doc.appendChild(ctml) ;
ctmlEntry.setAttribute(XMLTAG_ID, this.id);
ctmlEntry.setAttribute(XMLTAG_NAME, this.name);
ctmlEntry.setAttribute(XMLTAG_PROPERTY, this.property);
ctmlEntry.setAttribute(XMLTAG_STATUS, this.status);
ctmlEntry.setAttribute(XMLTAG_DESCRIPTION, this.desc);
ctmlEntry.setAttribute(XMLTAG_CREATE_TIME, Long
.toString(this.createTime));
Element policyList = doc.createElement(XMLTAG_POLICY_LIST);
ctmlEntry.appendChild(policyList);
2、将创建的xml格式的数据转化成byte数组
javax.xml.transform.Transformer transformer = TransformerFactory.newInstance()
.newTransformer() ;
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") ;
transformer.setOutputProperty(OutputKeys.INDENT, "yes") ;
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
StreamResult streamResult = new StreamResult(bos) ;
transformer.transform(new DOMSource(doc), streamResult) ;
return bos.toByteArray() ;

3\将byte数组转化成xml格式的数据
javax.xml.transform.dom.DOMResult docResult = new DOMResult() ;
transformer.transform(new StreamSource(new ByteArrayInputStream(
data)), docResult) ;
Document doc = (Document) docResult.getNode() ;
4\读取xml数据
生成根元素->获取根元素的节点列表-》将节点列表中的数据并转化成根元素Element-》通过根元素的getAttribute获取属性值,hasAttribute判断是否有属性
代码示例:org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader
Element root = doc.getDocumentElement();
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: