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

时间:2021-03-10 13:58:32

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.

我要添加的是一个人员节点,其元素在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);

4 个解决方案

#1


6  

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>

#2


1  

This is very easy with JOOX library, 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>");

#3


0  

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.

可以修改此选项以更新原始文件。

#4


-1  

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;
}

#1


6  

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>

#2


1  

This is very easy with JOOX library, 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>");

#3


0  

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.

可以修改此选项以更新原始文件。

#4


-1  

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;
}