org.w3c.dom.Document对象与字符串互转

    由于项目需要,需要我在现有的框架中去自己生成XML文档,而现有的框架中没有用到dom4j、jdom,而客户的要求是最好不好修改现有的框架,于是如下:

 

    1. 通过JDK自带的类把org.w3c.dom.Document转化为字符串。然后再用文件输出流输出,或者直接将ByteArrayOutputStream内存流换成输出流。

/**  
 * XML org.w3c.dom.Document 转 String  
 */ 
public static String docToString(Document doc) {   
    String xmlStr = "";   
    try {   
        TransformerFactory tf = TransformerFactory.newInstance();   
        Transformer t = tf.newTransformer();   
        t.setOutputProperty("encoding", "UTF-8");// 解决中文问题,试过用GBK不行   
        ByteArrayOutputStream bos = new ByteArrayOutputStream();   
        t.transform(new DOMSource(doc), new StreamResult(bos));   
        xmlStr = bos.toString();   
    } catch (TransformerConfigurationException e) {   
        e.printStackTrace();   
    } catch (TransformerException e) {   
        e.printStackTrace();   
    }   
    return xmlStr;   
}

 

    2. 利用jdk中自带的类将字符串转化为org.w3c.dom.Document。

/**  
 * String 转 XML org.w3c.dom.Document  
 */ 
public static Document stringToDoc(String xmlStr) {   
    Document doc = null;   
    try {   
        xmlStr = new String(xmlStr.getBytes(),"UTF-8");   
        StringReader sr = new StringReader(xmlStr);   
        InputSource is = new InputSource(sr);   
        DocumentBuilderFactory factory =  DocumentBuilderFactory.newInstance();   
        DocumentBuilder builder = factory.newDocumentBuilder();   
        doc = builder.parse(is);   
    } catch (ParserConfigurationException e) {      
        e.printStackTrace();   
    } catch (SAXException e) {        
        e.printStackTrace();   
    } catch (IOException e) {   
        e.printStackTrace();   
    }   
    return doc;   
}

 

你可能感兴趣的:(java,xml)