2011-06-20 54 views
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文件中插入更多標籤。

+0

你'nodes.getLength()''中爲loop'不獲取插入後刷新。 – RajeshS

回答

0
// Add a text node to the element 
element.appendChild(doc.createTextNode("D")); 

// Add a text node to the beginning of the element 
element.insertBefore(doc.createTextNode("A"), element.getFirstChild()); 

// Add a text node before the last child of the element 
element.insertBefore(doc.createTextNode("C"), element.getLastChild()); 

// Add another element after the first child of the root element 
Element element2 = doc.createElement("item"); 
element.insertBefore(element2, element.getFirstChild().getNextSibling()); 

// Add a text node in front of the new item element 
element2.getParentNode().insertBefore(doc.createTextNode("B"), element2); 

的代碼示例一塊,這將是有益的爲你增添