首页

关于granite源码包XMLUtil工具类获取DocumentBuilderFactory文档解析工厂、转xml文档为字符串等操作

标签:granite,XMLUtil工具类,DocumentBuilderFactory,TransformerFactory     发布时间:2018-05-22   

一、前言

基于granite源码包org.granite.util.XMLUtil工具类,通过xml文本字符串实例化org.w3c.dom.Document对象buildDocument、将org.w3c.dom.Document对象转为字符串toString、获取javax.xml.parsers.DocumentBuilderFactory对象文档构建工厂及构建javax.xml.transform.TransformerFactory对象等。

二、源码说明

package org.granite.util;@b@@b@import java.io.StringReader;@b@import java.io.StringWriter;@b@import javax.xml.parsers.DocumentBuilder;@b@import javax.xml.parsers.DocumentBuilderFactory;@b@import javax.xml.transform.Transformer;@b@import javax.xml.transform.TransformerFactory;@b@import javax.xml.transform.dom.DOMSource;@b@import javax.xml.transform.stream.StreamResult;@b@import org.w3c.dom.Document;@b@import org.xml.sax.InputSource;@b@@b@public class XMLUtil@b@{@b@  private DocumentBuilderFactory documentBuilderFactory = null;@b@  private TransformerFactory transformerFactory = null;@b@@b@  public Document buildDocument(String xml)@b@  {@b@    DocumentBuilder builder;@b@    try@b@    {@b@      builder = getDocumentBuilderFactory().newDocumentBuilder();@b@      return builder.parse(new InputSource(new StringReader(xml)));@b@    } catch (Exception e) {@b@      throw new RuntimeException("Could not parse XML string", e); }@b@  }@b@@b@  public String toString(Document doc) {@b@    Transformer transformer;@b@    try {@b@      transformer = getTransformerFactory().newTransformer();@b@      StringWriter writer = new StringWriter();@b@      transformer.transform(new DOMSource(doc), new StreamResult(writer));@b@      return writer.toString();@b@    } catch (Exception e) {@b@      throw new RuntimeException("Could not serialize document", e);@b@    }@b@  }@b@@b@  private TransformerFactory getTransformerFactory() {@b@    if (this.transformerFactory == null)@b@      this.transformerFactory = TransformerFactory.newInstance();@b@    return this.transformerFactory;@b@  }@b@@b@  private DocumentBuilderFactory getDocumentBuilderFactory() {@b@    if (this.documentBuilderFactory == null)@b@      this.documentBuilderFactory = DocumentBuilderFactory.newInstance();@b@    return this.documentBuilderFactory;@b@  }@b@}


<<热门下载>>