• 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文件的实体
  • 相关阅读:
    通过唯一ID实现简单的日志跟踪实现
    从零单排入门机器学习:Octave/matlab的经常使用知识之矩阵和向量
    zoj 1671 Walking Ant
    JDBC基础
    Android从源码看ListView的重用机制
    JavaScript设计模式 Item9 --适配器模式Adapter
    C++11新特性之 std::forward(完美转发)
    [组合数]求组合数的几种方法总结
    HDU 4005 The war(双连通好题)
    Workspace in use or cannot be created, choose a different one.--错误解决的方法
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5494987.html
Copyright © 2020-2023  润新知