5

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

因此,我们将不胜感激,谢谢。

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

1 回答 1

11

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

这是一个两步过程:

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 等。

于 2011-05-12T13:07:42.727 回答