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文件的实体
  • 相关阅读:
    webmagic的使用学习
    redis在macOS上的安装及与springboot的整合使用
    Swagger-UI
    个人作业——软件工程实践总结&个人技术博客
    祝贺大野鸡喜提小黄衫一件
    软件评测(个人作业)
    结对第二次作业
    Springboot项目创建文件中相对路径问题
    二进制翻转
    欧拉降幂及广义欧拉降幂证明
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5494987.html
Copyright © 2011-2022 走看看