zoukankan      html  css  js  c++  java
  • String 和 document 的相互转换总结

    转自:http://blog.sina.com.cn/s/blog_7f865faf01014qrs.html

    一、使用最原始的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。

  • 相关阅读:
    互联网、云大数据相关书籍推荐
    育儿、教育书籍推荐
    MySQL客户端工具的选择
    解决Windows10或者其他版本Windows Update报错的问题
    启动Myeclipse报错“Failed to create the Java Virtual Machine”的解决办法
    mysql的日期存储字段比较int,datetime,timestamp区别
    nginx增加ssl服务方法
    mysql导入出现MySQL Error 1153
    mysql忘记密码修改方法
    清空本地ssh记录数据,ssh: connect to host Ip port 22: Connection refused
  • 原文地址:https://www.cnblogs.com/x_wukong/p/4718003.html
Copyright © 2011-2022 走看看