package org.xml.example; import java.io.File; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Demo3 { public static void main(String[] args) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = documentBuilderFactory.newDocumentBuilder(); Document document = builder.newDocument(); Element root = document.createElement("language"); root.setAttribute("cat", "it"); Element lan1 = document.createElement("lan"); lan1.setAttribute("id" , "1"); Element name1 = document.createElement("name"); name1.setTextContent("java"); Element ide1 = document.createElement("ide"); ide1.setTextContent("myeclipse"); lan1.appendChild(name1); lan1.appendChild(ide1); root.appendChild(lan1); document.appendChild(root); //创建转换工厂,然后将创建的document转换输出到文件中或控制台 TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(new DOMSource(document), new StreamResult(new File("newXml.xml")));
//将document中的信息转换为字符串输出到控制台中 StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); System.out.println(stringWriter.toString()); } catch (Exception e) { e.printStackTrace(); } } }
该文件创建放在项目中路径中
成功的结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <language cat="it"> <lan id="1"> <name>java</name> <ide>myeclipse</ide> </lan> </language>