zoukankan      html  css  js  c++  java
  • java 生成xml文件

    这里也使用的是import org.w3c.dom.Document;

    首先创建document对象,给该对象赋值,然后将document对象使用transformer的transformer转换方法转换成文件或者其他类型进行想要的操作。

    1、创建DocumentBuilder对象

    DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
                DocumentBuilder    documentBuilder = documentBuilderFactory.newDocumentBuilder();

    2、创建Document对象并赋值

    DocumentBuilder的api:http://download.oracle.com/technetwork/java/javase/6/docs/zh/api/javax/xml/parsers/DocumentBuilder.html#parse%28java.lang.String%29

     Document document=documentBuilder.parse(uri);//我这里使用的是parse方法解析uri地址的文件内容,将该内容转换成字符串
    //这里使用的是新建空的document,然后给document填充内容,发现document的子节点都是使用appendChildNode()一层层加上去的,控件使用的都是document
    。createElement得到Element对象。setTextContent给标签内容赋值
    Document document=documentBuilder.newDocument(); Element root=document.createElement("language"); root.setAttribute("cat","it"); Element lan1=document.createElement("lan"); lan1.setAttribute("id", "1"); Element name1=document.createElement("name"); Element ide1=document.createElement("ide"); name1.setTextContent("java"); ide1.setTextContent("eclipes"); Element lan2=document.createElement("lan"); lan2.setAttribute("id", "2"); Element name2=document.createElement("name"); Element ide2=document.createElement("ide"); name2.setTextContent("Switf"); ide2.setTextContent("x-code"); Element lan3=document.createElement("lan"); lan1.setAttribute("id", "3"); Element name3=document.createElement("name"); Element ide3=document.createElement("ide"); name3.setTextContent("c#"); ide1.setTextContent("visual"); lan1.appendChild(name1); lan1.appendChild(ide1); lan2.appendChild(name2); lan2.appendChild(ide2); lan3.appendChild(name3); lan3.appendChild(ide3); root.appendChild(lan1); root.appendChild(lan2); root.appendChild(lan3); document.appendChild(root);

    创建document空对象并赋值例子:

    3、转换document成xml文件

    /* 生成transformer对象 */
    TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer();
    StringWriter writer=new StringWriter(); /*字符输出流*/
    transformer.transformer(new DOMSource(document),new StreamResult(writer));//将document中的值转换到输出流中
    System.out.println(writer.toString());
    File xmlfile=new File("newxml.xml");
    transformer.transformer(new DOMSource(document),new StreamResult(xmlfile));//将document中的值写入file文件中,自动完成file文件的实体
  • 相关阅读:
    MYSQL函数 Cast和convert的用法详解
    MySQL5.7.9(GA)的安装
    TMS Scripter importtool的使用
    MySQL 高可用架构在业务层面的应用分析
    UNIGUI:How to redirect and close session?
    HTML URL 编码:请参阅:http://www.w3school.com.cn/tags/html_ref_urlencode.html
    js 解决函数加载的问题
    必备函数
    Action 分离
    JavaScript.Remove
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5494987.html
Copyright © 2011-2022 走看看