I've already read through a few of the answers on this site but none of them worked for me. I have an XML file like this:
<root>
<character>
<name>Volstvok</name>
<charID>(omitted)</charID>
<userID>(omitted)</userID>
<apiKey>(omitted)</apiKey>
</character>
</root>
I need t开发者_StackOverflow中文版o add another <character>
somehow.
I'm trying this but it does not work:
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);
}
Without seeing all your code, I suspect the problem is that you're adjusting the in-memory DOM, but not writing the result back to the file.
Writing it out looks something like:
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(doc),
new StreamResult(f));
where doc
is a Document, and f
is the File to write to.
In order to find particular elements in a DOM, I recommend XPath.
精彩评论