2012-03-02 34 views
0

如何在運行時使用java程序動態編輯xml文件。例如,我有這樣的xml文件,在運行時動態更新xml文件

<chart> 
<set label="Item A" value="4"/> 
<set label="Item B" value="5"/> 
<set label="Item C" ``alue="6"/> 
<set label="Item D" value="7"/> 
</chart> 

我已經嘗試jdom API在運行時更新xml。但它只能編輯單個值標籤。但在這裏我有同名的多標籤。我想在運行時爲每個標籤動態更改值。任何人都可以給我提出任何想法。

回答

0

假設你正在使用JDOM-1.1.2.jar

Document doc = (Document) builder.build(YourFileName); 
Element rootNode = doc.getRootElement(); 
List<Element> childrenNode = rootNode.getChildren(); 
     for (Element child : childrenNode) { 
      System.out.println(child.getAttribute("value").getIntValue()); 
      child.getAttribute("value").setValue("2"); 
     } 

// print updates to xml file with good formatting 
XMLOutputter xmlOutput = new XMLOutputter(); 
xmlOutput.setFormat(Format.getPrettyFormat()); 
xmlOutput.output(doc, new FileWriter(YourFileName)); 
+0

謝謝你的答案的朋友。我使用dom4j API完成了這項任務。無論如何非常感謝您的答案.. – 2012-03-02 11:50:25