zoukankan      html  css  js  c++  java
  • java string转为xml

        一、使用最原始的javax.xml.parsers,标准的jdk api  
          
        // 字符串转XML  
        String xmlStr = "......";  
        StringReader sr = new StringReader(xmlStr);  
        InputSource is = new InputSource(sr);  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder=factory.newDocumentBuilder();  
        Document doc = builder.parse(is);  
          
        //XML转字符串  
        TransformerFactory  tf  =  TransformerFactory.newInstance();  
        Transformer t = tf.newTransformer();  
        t.setOutputProperty("encoding","GB23121");//解决中文问题,试过用GBK不行  
        ByteArrayOutputStream  bos  =  new  ByteArrayOutputStream();  
        t.transform(new DOMSource(doc), new StreamResult(bos));  
        String xmlStr = bos.toString();  
          
        这里的XML DOCUMENT为org.w3c.dom.Document  
          
          二、使用dom4j后程式变得更简单  
          
        // 字符串转XML  
        String xmlStr = "......";  
        Document document = DocumentHelper.parseText(xmlStr);  
          
        // XML转字符串  
        Document document = ...;  
        String text = document.asXML();  
          
        这里的XML DOCUMENT为org.dom4j.Document  
          
          三、使用JDOM  
          
        JDOM的处理方式和第一种方法处理很类似  
          
        //字符串转XML  
        String xmlStr = ".....";  
        StringReader sr = new StringReader(xmlStr);  
        InputSource is = new InputSource(sr);  
        Document doc = (new SAXBuilder()).build(is);  
          
        //XML转字符串  
        Format format = Format.getPrettyFormat();  
        format.setEncoding("gb2312");//配置xml文档的字符为gb2312,解决中文问题  
        XMLOutputter xmlout = new XMLOutputter(format);  
        ByteArrayOutputStream bo = new ByteArrayOutputStream();  
        xmlout.output(doc,bo);  
        String xmlStr = bo.toString();  
          
        这里的XML DOCUMENT为org.jdom.Document  
          
          四、JAVASCRIPT中的处理  
          
        //字符串转XML  
        var xmlStr = ".....";  
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
        xmlDoc.async=false;  
        xmlDoc.loadXML(xmlStr);  
        //能够处理这个xmlDoc了  
        var name = xmlDoc.selectSingleNode("/person/name");  
        alert(name.text);  
          
        //XML转字符串  
        var xmlDoc = ......;  
        var xmlStr = xmlDoc.xml  
          
        这里的XML DOCUMENT为javascript版的XMLDOM  
    
  • 相关阅读:
    js数组去重
    js和jq实现全选反选
    js的作用域深入理解
    js对数组的常用操作
    如何写出让java虚拟机发生内存溢出异常OutOfMemoryError的代码
    JAVA编程思想(第四版)学习笔记----4.8 switch(知识点已更新)
    通过拦截器Interceptor实现Spring MVC中Controller接口访问信息的记录
    JAVA编程思想(第四版)学习笔记----11.10 Map
    JAVA中的for-each循环与迭代
    JAVA编程思想(第四版)学习笔记----11.5 List,11.6迭代器
  • 原文地址:https://www.cnblogs.com/interdrp/p/5822018.html
Copyright © 2011-2022 走看看