在xml文件中插入节点

时间:2012-04-14 18:46:01

标签: java xml dom insert

我想使用Java DOM在xml文件中插入一个节点。我实际上正在编辑一个虚拟文件的很多内容,以便像原版一样进行编码。

我想在以下文件之间添加一个开放节点和关闭节点;

            <?xml version="1.0" encoding="utf-8"?>
            <Memory xmlns:xyz="http://www.w3.org/2001/XMLSchema-instance"   
            xmlns:abc="http://www.w3.org/2001/XMLSchema" Derivative="ABC"            
            xmlns="http://..">

       ///////////<Address> ///////////(which I would like to insert)

            <Block ---------
            --------
            -------
            />

      ////////// </Address> /////////(which I would like to insert)

            <Parameters Thread ="yyyy" />
            </Memory>

我特此请求您告诉我如何在xml文件之间插入?

提前致谢。!

我尝试过的是;

            Element child = doc.createElement("Address");
    child.appendChild(doc.createTextNode("Block"));
    root.appendChild(child);

但这给了我一个像<; p>这样的输出

        <Address> Block </Address> and not the way i expect :(

现在,我尝试过添加这些行;

            Element cd = doc.createElement("Address");
            Node Block = root.getFirstChild().getNextSibling();
        cd.appendChild(Block);
        root.insertBefore(cd, root.getFirstChild());

但是,这不是我要找的输出。我把这个输出作为                ---------

3 个答案:

答案 0 :(得分:2)

你想要的可能是:

Node parent = block.getParentNode()
Node blockRemoved = parent.removeChild(block);
// Create address
parent.appendChild(address);
address.appendChild(blockRemoved);

这是在W3C DOM下重新连接节点的标准方法。

答案 1 :(得分:1)

下面:

DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = b.parse(...);

// Parent of existing Block elements and new Address elemet
// Might be retrieved differently depending on 
// actual structure
Element parent = document.getDocumentElement();
Element address = document.createElement("address");

NodeList nl = parent.getElementsByTagName("Block");
for (int i = 0; i < nl.getLength(); ++i) {
    Element block = (Element) nl.item(i);
    if (i == 0)
        parent.insertBefore(address, block);
    parent.removeChild(block);
    address.appendChild(block);
}

// UPDATE: how to pretty print

LSSerializer serializer = 
    ((DOMImplementationLS)document.getImplementation()).createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput output = 
    ((DOMImplementationLS)document.getImplementation()).createLSOutput();
output.setByteStream(System.out);
serializer.write(document, output);

答案 2 :(得分:0)

我假设您使用的是W3C DOM(例如http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html)。如果是这样,试试

insertBefore(address, block);