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文件的实体
  • 相关阅读:
    百度之星资格赛1001——找规律——大搬家
    HDU1025——LIS——Constructing Roads In JGShining's Kingdom
    DP(递归打印路径) UVA 662 Fast Food
    递推DP UVA 607 Scheduling Lectures
    递推DP UVA 590 Always on the run
    递推DP UVA 473 Raucous Rockers
    博弈 HDOJ 4371 Alice and Bob
    DFS(深度) hihoCoder挑战赛14 B 赛车
    Codeforces Round #318 [RussianCodeCup Thanks-Round] (Div. 2)
    DP(DAG) UVA 437 The Tower of Babylon
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5494987.html
Copyright © 2011-2022 走看看