2

我有以下 XML,我想在 xml 中添加另一个“产品”。

<?xml version="1.0" encoding="ISO-8859-1"?>
<products>
    <product>
        <name>Computer</name>
        <code>PC1003</code>
        <description>Basic Computer</description>
        <price>399.99</price>
    </product>
    <product>
        <name>Monitor</name>
        <code>MN1003</code>
        <description>LCD Monitor</description>
        <price>99.99</price>
    </product>
    <product>
        <name>Printer</name>
        <code>PR1003x</code>
        <description>Inkjet Printer</description>
        <price>54.23</price>
    </product>
</products>

这是我到目前为止的代码:

        // Variables
        File file = new File("db_products.xml"); // set xml to parse

        // Create builders
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(file); // load xml file
        doc.getDocumentElement().normalize();

        doc.createElement("product");

我真的不在乎在哪里添加了新的“产品”部分。我似乎无法理解节点和元素之间的区别。我假设添加新“产品”部分的正确方法是将子项添加到“产品”,然后将子项(名称、代码等)添加到“产品”。

任何有关如何轻松执行此操作的帮助或指向简单教程的链接将不胜感激。

4

1 回答 1

3

您需要做的是products首先检索元素,然后appendChild在该元素上调用。像这样的东西:

Element productElement = doc.createElement("product");
productElement.setAttribute("name", "value");
//Other name value pairs...

//Append the products element to the right spot.
Element productsElement = (Element) doc.getElementByTagName("products").item(0);
productsElement.appendChild(productElement);

//Convert doc to xml string
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
String xmlAsString = writer.toString();
于 2012-12-17T23:13:30.770 回答