我看不出用 DOM 做这件事有什么问题。
代码:
public static void main(String[] args) throws ParserConfigurationException, IOException, TransformerException
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("root");
document.appendChild(root);
Element emp1 = document.createElement("employee");
Element emp1name = document.createElement("name");
emp1name.setTextContent("Mohammad");
emp1.appendChild(emp1name);
Element emp2 = document.createElement("employee");
Element emp2name = document.createElement("name");
emp2name.setTextContent("Ali");
emp2.appendChild(emp2name);
root.appendChild(emp1);
root.appendChild(emp2);
printDocument(document, System.out);
}
输出:
<root>
<employee>
<name>Mohammad</name>
</employee>
<employee>
<name>Ali</name>
</employee>
</root>
printDocument
您可以在此SO Answer中查看源代码。
完整的源代码可以在这里找到。