zoukankan      html  css  js  c++  java
  • 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。

    下面这篇文章也不错,专门介绍dom4j操作的

    http://blog.csdn.net/redarmy_chen/article/details/12969219

  • 相关阅读:
    Jquery基础知识与使用
    JavaScript人机交互
    CSS和JS基础
    Html基础
    Struts2第一天:Struts2的概述、Struts2的入门、Struts2常见的配置、Struts2的Action的编写
    MyEclipse中设置类的注释(修改时间,作者等)
    Failed to initialize end point associated with ProtocolHandler ["http-bio-80"] java.net.BindExce问题解决
    Hibernate第四天:Hibernate的查询方式、抓取策略
    Hibernate第三天:Hibernate的一对多配置、Hibernate的多对多的配置
    Neural Network(神经网络)
  • 原文地址:https://www.cnblogs.com/majw/p/6698420.html
Copyright © 2011-2022 走看看