2010-05-15 2 views
0

이미이 사이트에서 몇 가지 답변을 읽었지만 그 중 아무 것도 저에게 효과가 없었습니다.Java appending XML 데이터

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

어떻게 든 다른 <character>을 추가해야합니다 :이 같은 XML 파일이 있습니다.

나는이 노력하고있어하지만이 작동하지 않습니다

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