使用 java 将节点附加到现有的 XML 文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21240030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:34:28  来源:igfitidea点击:

Append nodes into existing XML File with java

javaxml

提问by user3216026

Hi im looking for a solution to append nodes from java into an existing xml file. What i got is an xml file like this

嗨,我正在寻找将节点从 java 附加到现有 xml 文件的解决方案。我得到的是一个像这样的 xml 文件

<data>
<people>
    <person>
        <firstName>Frank</firstName>
        <lastName>Erb</lastName>
        <access>true</access>
        <images>
            <img>hm001.jpg</img>
        </images>
    </person>
    <person>
        <firstName>Hans</firstName>
        <lastName>Mustermann</lastName>
        <access>true</access>
        <images>
            <img>hm001.jpg</img>
        </images>
    </person>
    <person>
        <firstName>Thomas</firstName>
        <lastName>Tester</lastName>
        <access>false</access>
        <images>
            <img>tt001.jpg</img>
        </images>
    </person>
</people>
 </data>

what i whant to add is a person node with its elements inside the people element. My big problem is the data node which is root node. If it would be the Person node as root I could solve it. But I can't manage to get the person nodes under the people node.

我要添加的是一个 person 节点,其元素位于 people 元素内。我的大问题是作为根节点的数据节点。如果它是作为 root 的 Person 节点,我可以解决它。但是我无法在人员节点下获得人员节点。

           <person>
        <firstName>Tom</firstName>
        <lastName>Hanks</lastName>
        <access>false</access>
        <images>
            <img>tt001.jpg</img>
        </images>
    </person>

thanks for your help!

感谢您的帮助!

my java code looks as far like this

我的java代码看起来像这样

Element root = document.getDocumentElement();


// Root Element
Element rootElement = document.getDocumentElement();

Collection<Server> svr = new ArrayList<Server>();
svr.add(new Server());

for (Server i : svr) {
    // server elements

    Element server = document.createElement("people");
    rootElement.appendChild(server);
    //rootElement.appendChild(server);

    Element name = document.createElement("person");
    server.appendChild(name);

    Element firstName = document.createElement("firstName");
    firstName.appendChild(document.createTextNode(i.getFirstName()));
    server.appendChild(firstName);
    name.appendChild(firstName);

    Element port = document.createElement("lastName");
    port.appendChild(document.createTextNode(i.getLastName()));
    server.appendChild(port); 
    name.appendChild(port);

    Element access = document.createElement("access");
    access.appendChild(document.createTextNode(i.getAccess()));
    server.appendChild(access); 
    name.appendChild(access);

    String imageName = Main.randomImgNr+"";
    Element images = document.createElement("images");
    //images.appendChild(document.createTextNode(i.getAccess()));
    Element img = document.createElement("img");
    img.appendChild(document.createTextNode(imageName));//i.getImage()));
    images.appendChild(img);            

    server.appendChild(images);
    name.appendChild(images);
    root.appendChild(server);

采纳答案by Felipe T.

Without a library you can do something like this:

没有图书馆,你可以做这样的事情:

Element dataTag = doc.getDocumentElement();
Element peopleTag =  (Element) dataTag.getElementsByTagName("people").item(0);

Element newPerson = doc.createElement("person");

Element firstName = doc.createElement("firstName");
firstName.setTextContent("Tom");

Element lastName = doc.createElement("lastName");
lastName.setTextContent("Hanks");

newPerson.appendChild(firstName);
newPerson.appendChild(lastName);

peopleTag.appendChild(newPerson);

Which results:

结果:

...
        <person>
            <firstName>Thomas</firstName>
            <lastName>Tester</lastName>
            <access>false</access>
            <images>
                <img>tt001.jpg</img>
            </images>
        </person>
        <person>
            <firstName>Tom</firstName>
            <lastName>Hanks</lastName>
        </person>
    </people>
</data>

回答by MariuszS

This is very easy with JOOXlibrary, examples:

使用JOOX库,这很容易,示例:

// Parse the document from a file
Document document = $(xmlFile).document();

// Find the order at index 4 and add an element "paid"
$(document).find("people").children().eq(4).append("<paid>true</paid>");

// Find those orders that are paid and flag them as "settled"
$(document).find("people").children().find("paid").after("<settled>true</settled>");

回答by Wayne

Follow this general approach:

请遵循以下通用方法:

public static void main(String[] args) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();
        Document doc = db.parse("input.xml");
        NodeList people = doc.getElementsByTagName("people");
        people.item(0)
                .appendChild(
                        createPersonElement(doc, "Tom", "Hanks", true,
                                "tt001.jpg"));
        System.out.println(nodeToString(doc));
    } catch (SAXException e) {
        // handle SAXException
    } catch (IOException e) {
        // handle IOException
    } catch (TransformerException e) {
        // handle TransformerException
    } catch (ParserConfigurationException e1) {
        // handle ParserConfigurationException
    }
}

private static Element createPersonElement(Document doc, String firstName,
        String lastName, Boolean access, String image) {
    Element el = doc.createElement("person");
    el.appendChild(createPersonDetailElement(doc, "firstName", firstName));
    el.appendChild(createPersonDetailElement(doc, "lastName", lastName));
    el.appendChild(createPersonDetailElement(doc, "access",
            access.toString()));
    Element images = doc.createElement("images");
    images.appendChild(createPersonDetailElement(doc, "img", image));
    el.appendChild(images);
    return el;
}

private static Element createPersonDetailElement(Document doc, String name,
        String value) {
    Element el = doc.createElement(name);
    el.appendChild(doc.createTextNode(value));
    return el;
}

This uses the following helper method to print the results:

这使用以下辅助方法来打印结果:

private static String nodeToString(Node node) throws TransformerException {
    StringWriter buf = new StringWriter();
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.transform(new DOMSource(node), new StreamResult(buf));
    return buf.toString();
}

This could be modified to update the original file instead.

这可以修改为更新原始文件。

回答by Nandkishor Mewara

public static void main(String[] args) throws ParserConfigurationException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    db = null;
    try {
        db = dbf.newDocumentBuilder();
        Document doc = db.parse("input.xml");
        NodeList people = doc.getElementsByTagName("people");
        people.item(0).appendChild(createPersonElement(doc, "Tom", "Hanks", true, "tt001.jpg"));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult console = new StreamResult(System.out);//for Console print
        transformer.transform(source, console);
        StreamResult file = new StreamResult(new File("input.xml"));
        transformer.transform(source, file);
    } catch (SAXException | IOException | TransformerException | ParserConfigurationException e) {
        System.out.println(e);
    }
}

private static Element createPersonElement(Document doc, String firstName,
        String lastName, Boolean access, String image) {
    Element el = doc.createElement("person");
    el.appendChild(createPersonDetailElement(doc, "firstName", firstName));
    el.appendChild(createPersonDetailElement(doc, "lastName", lastName));
    el.appendChild(createPersonDetailElement(doc, "access",
            access.toString()));
    Element images = doc.createElement("images");
    images.appendChild(createPersonDetailElement(doc, "img", image));
    el.appendChild(images);
    return el;
}

private static Element createPersonDetailElement(Document doc, String name,
        String value) {
    Element el = doc.createElement(name);
    el.appendChild(doc.createTextNode(value));
    return el;
}