2015-09-01 29 views
0

我已經以下面的方式創建的XML更新XML內部的元件:使用DOM

public static Document baseTemplate(String topLevel,String[] pkey) throws ParserConfigurationException{ 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    Document doc = builder.newDocument(); 
    Element top = doc.createElement(topLevel); 
    for(int i= 0;i<pkey.length;i++){ 
     Element child = doc.createElement(pkey[i]); 
     top.appendChild(child);   
    } 
    doc.appendChild(top); 
    return doc; 
} 

這就產生了一個虛設的xml諸如基於通過了頂層和在其內各個元件的輸入。

現在我希望能夠稍後用值更新各個元素。基於傳入的輸入,xml結構將是泛型的。類似地,更新邏輯也是泛型的。我該如何實現它?

+0

你如何達到目的? – Andreas

回答

0

只是一個想法,「使用XPath編輯XML或創建XML」,對於每一個新的輸入通過你需要有XPATH高達要更新,請嘗試是這樣的節點是標籤:

Document doc = /*you have this in your code */ 
XModifier modifier = new XModifier(doc); 
modifier.addModify("//PersonList/Person[2]/Name", "newName"); 
modifier.modify(); 

你可以找到更多關於XModifier這裏:https://github.com/shenghai/xmodifier 希望這將幫助你。