DOM 解析器 - 创建 XML 文档
演示示例
以下是我们需要创建的 XML −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars><supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars></cars>
演示示例
CreateXmlFileDemo.java
package com.tutorialspoint.xml; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; 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.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; public class CreateXmlFileDemo { public static void main(String argv[]) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // 根元素 Element rootElement = doc.createElement("cars"); doc.appendChild(rootElement); // supercars 元素 Element supercar = doc.createElement("supercars"); rootElement.appendChild(supercar); // 将属性设置为元素 Attr attr = doc.createAttribute("company"); attr.setValue("Ferrari"); supercar.setAttributeNode(attr); // carname 元素 Element carname = doc.createElement("carname"); Attr attrType = doc.createAttribute("type"); attrType.setValue("formula one"); carname.setAttributeNode(attrType); carname.appendChild( doc.createTextNode("Ferrari 101")); supercar.appendChild(carname); Element carname1 = doc.createElement("carname"); Attr attrType1 = doc.createAttribute("type"); attrType1.setValue("sports"); carname1.setAttributeNode(attrType1); carname1.appendChild( doc.createTextNode("Ferrari 202")); supercar.appendChild(carname1); // 将内容写入 xml 文件 TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\cars.xml")); transformer.transform(source, result); // 输出到控制台进行测试 StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } } }
上述程序将生成以下结果 −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars><supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars></cars>