0
我有一個XML文檔,我想插入更多數量的標籤。例如 <data> <tag1>1St tag</tag1> <tag2>2nd tag</tag2> <tag3>NewTag</tag3> <tag4>4th tag</tag4> </data>
如何在xml文件中插入標籤
我試圖插入數據,但每當我插入數據發生在一次
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("File.xml"));
NodeList nodes = doc.getElementsByTagName("tag4");
Text a = doc.createTextNode("value");
Element p = doc.createElement("tag3");
p.appendChild(a);
for (int i = 0; i < nodes.getLength(); i++) {
nodes.item(i).getParentNode().insertBefore(p, nodes.item(i));
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlOutput = result.getWriter().toString();
System.out.println(xmlOutput);
System.out.println("Done");
插入元件該代碼被添加新的元件,但每當我插入新標記它重寫新標記名稱到現有標記中。如何糾正這個問題。爲了簡單起見,我想在XML文件中插入更多標籤。
你'nodes.getLength()''中爲loop'不獲取插入後刷新。 – RajeshS