使用Java复制某些节点

时间:2011-05-12 12:32:38

标签: java xml copy rft

我正在尝试在JAVA中读取/复制xml文档的某个部分,然后将此部分另存为新的xml文档。因此,在下面的示例中,您可以看到studentinfo和联系信息,我只想选择studentinfo并复制整个区域,以便节点和元素。 我只能找到有关仅选择元素或仅选择节点的信息。

所以请帮助,谢谢。

<header>
<body>
    <studentinfo>
        <name>Student Name<name>
        <studentid>0987654321<studentid>
        <Location>USA<Location>
    <studentinfo>
    <contactinfo>
        <email>email@email.com<email>
        <address>somewhere 1<address>
        <postalcode>123456<postalcode>
    <contactinfo>
<body>
<header>

1 个答案:

答案 0 :(得分:10)

我要做一个很大的假设,那就是你使用的是org.w3c.dom.Document api。

这是一个两步过程:

Document doc = parse(xmlSource);

Document targetDoc = openTargetDoc();
Node copyTo = findWhereYouWantToCopyStuffTo(targetDoc);

// Find the node or nodes to want to copy.. could use XPath or some other search
NodeList studentinfoList = doc.getElementsByTagName("studentinfo");

// for each found... make a copy (via importNode) and attach to some point in the target doc
for( int i = 0; i < studnetinfoList.getLength(); i ++ ){
    Node n = studentinfoList.item(i);
    Node copyOfn = targetDoc.importNode(n,true);
    copyTo.appendChild(copyOfn);
}

如果这不是你想要的,你可能需要添加一些你想要复制的细节和使用api等的地方。