繁体   English   中英

Java附加XML数据

[英]Java appending XML data

我已经阅读了本网站上的一些答案,但没有一个对我有用。 我有一个像这样的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);
}

没有看到所有代码,我怀疑问题是您正在调整内存中的DOM,但没有将结果写回到文件中。

写出来看起来像:

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

其中doc是文档,而f是要写入的文件。

为了找到DOM中的特定元素,我建议使用XPath

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM