package com.test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class Test {
public static void main(String arg[]){
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = null;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = documentBuilder.newDocument();
//设置没有dtd和schema作为该XML的约束文档,且不显示该属性
document.setXmlStandalone(true);
Element pserson = document.createElement("Pserson");
Element name = document.createElement("name");
Element email = document.createElement("email");
pserson.appendChild(email);
pserson.appendChild(name);
name.setTextContent("xxxx");
name.setAttribute("type","String");
email.setTextContent("33");
email.setAttribute("type","int");
document.appendChild(pserson);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transformerFactory.newTransformer();
//格式化生成的xml结构
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.transform(new DOMSource(document),new StreamResult(new File("D://k.xml")));
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}