2010-05-15 60 views
0

我已經通讀了本網站上的一些答案,但沒有一個爲我工作。我有這樣一個XML文件:Java附加XML數據

<root> 
    <character> 
     <name>Volstvok</name> 
     <charID>(omitted)</charID> 
     <userID>(omitted)</userID> 
     <apiKey>(omitted)</apiKey> 
    </character> 
</root> 

我需要添加另一個<character>莫名其妙。

我想這一點,但它不工作:

public void addCharacter(String name, int id, int userID, String apiKey){ 
    Element newCharacter = doc.createElement("character"); 

    Element newName = doc.createElement("name"); 
    newName.setTextContent(name); 

    Element newID = doc.createElement("charID"); 
    newID.setTextContent(Integer.toString(id)); 

    Element newUserID = doc.createElement("userID"); 
    newUserID.setTextContent(Integer.toString(userID)); 

    Element newApiKey = doc.createElement("apiKey"); 
    newApiKey.setTextContent(apiKey); 

    //Setup and write 
    newCharacter.appendChild(newName); 
    newCharacter.appendChild(newID); 
    newCharacter.appendChild(newUserID); 
    newCharacter.appendChild(newApiKey); 
    doc.getDocumentElement().appendChild(newCharacter); 
} 

回答

0

沒有看到所有的代碼,我懷疑的問題是,要調整的內存中的DOM,但不寫回結果到文件。

寫出來看起來像:

TransformerFactory.newInstance().newTransformer() 
        .transform(new DOMSource(doc), 
          new StreamResult(f)); 

其中doc是一個文檔,並f是寫入文件。

爲了找到DOM中的特定元素,我推薦使用XPath

+0

工作,謝謝! 現在,如果沒有太多的麻煩,你能告訴我如何根據它在XML文件中的位置來刪除嗎? – Travis 2010-05-15 04:47:02