0
我想使用DOM解析器創建一個xml。下面是我創建XML的代碼。但我正在逐漸其中只有XML版本下面給出一個xml:使用DOM創建XML時創建空XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
用於生成XML的代碼如下:
private void createTestngXML() throws Exception {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
document.setXmlVersion("1.0");
Element root = document.createElement("suite");
root.setAttribute("name", "MasterDataSuite");
root.setAttribute("verbose", "1");
Element testnode = document.createElement("test");
testnode.setAttribute("name", "MasterDataTests");
root.appendChild(testnode);
Element classesNode = document.createElement("classes");
testnode.appendChild(classesNode);
Element classNode = document.createElement("class");
classNode.setAttribute("com.test.suite.TestSuite1.java");
classesNode.appendChild(classNode);
Element classNode = document.createElement("class");
classNode.setAttribute("com.test.suite.TestSuite2.java");
classesNode.appendChild(classNode);
document.appendChild(root);
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(new File("D:\\testng.xml"));
transformer.transform(source, result);
} catch (Exception ex) {
throw ex;
}
}
,但創造的節點在不產生xml文件。我究竟做錯了什麼?
添加 「document.appendChild(根);」到你的樣品。 –