我有以下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");
我并不关心添加新“产品”部分的位置。我似乎无法理解节点和元素之间的区别。我假设添加新“产品”部分的正确方法是将子项添加到“产品”,然后将子项(名称,代码等)添加到“产品”。
任何有关如何轻松完成此操作的帮助,或者指向简单教程的链接都将受到赞赏。
答案 0 :(得分: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();