package example01;
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.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
public class doit {
public static void main(String[] args) {
Document doc = createDocument();
Element root = doc.createElement("students");
doc.appendChild(root);
addStudentInfo(doc,root,"王宏","20100101","96","88","90");
addStudentInfo(doc,root,"李娜","20100102","75","56","70");
addStudentInfo(doc,root,"孙武","20100103","77","70","20");
outputXMLFile(doc,"student.xml");
}
/* 通过DOM解析器创建一个空的Document对象 */
public static Document createDocument() {
// 通过newInstance方法创建DocumentBuilderFactory对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
// 创建解析器对象
DocumentBuilder db = dbf.newDocumentBuilder();
// 创建一个空的Document对象
doc = db.newDocument();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return doc;
}
public static void addStudentInfo(Document doc,Element root,String studentName,String studentId,String javaContent,String OracleContent,String umlContent){
Element student = doc.createElement("student");
student.setAttribute("id",studentId);
root.appendChild(student);
Element name = doc.createElement("name");
name.setTextContent(studentName);
student.appendChild(name);
Element java = doc.createElement("java");
java.setTextContent(javaContent);
student.appendChild(java);
Element oracle = doc.createElement("oracle");
oracle.setTextContent(OracleContent);
student.appendChild(oracle);
Element uml = doc.createElement("uml");
uml.setTextContent(umlContent);
student.appendChild(uml);
}
/* 将内存中的DOM树输出为一个xml文档 */
public static void outputXMLFile(Document doc,String filename) {
try {
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
//设置输出XML文件的换行
tf.setOutputProperty(OutputKeys.INDENT, "yes");
//设置输出XML文件的缩进
tf.setOutputProperty("{https://xml.apache.org/xslt}indent-amount", "4");
//把DOM对象转换为XML对象
DOMSource source = new DOMSource(doc);
//创建一个输出XML文件对象
//StreamResult result = new StreamResult(new File(filename));
StreamResult result = new StreamResult(new PrintStream(new FileOutputStream(filename),true, StandardCharsets.UTF_8));
//把XML源代码输出为XML文件
tf.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}package example01;
import org.w3c.dom.D