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

时间:2014-01-20 17:08:08

标签: java xml

您好我正在寻找一种解决方案,将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>

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

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

感谢您的帮助!

我的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 个答案:

答案 0 :(得分:7)

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

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

结果如何:

...
        <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>

答案 1 :(得分:1)

使用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>");

答案 2 :(得分:0)

遵循这种一般方法:

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

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

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

可以修改它以更新原始文件。

答案 3 :(得分:-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;
}