2010-05-15 61 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