拆分xml节点 [英] Splitting xml nodes

查看:132
本文介绍了拆分xml节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个xml:

<Forms>
<Form ID="230688" TemplateID="1111" DocType="1">
    <Field name="topmostSubform[0].Page1[0].Street[0]" value="street" />
    <Field name="topmostSubform[0].Page1[0].HouseNo[0]" value="18" />
</Form>
<Form ID="230645" TemplateID="5444" DocType="8">
    <Field name="topmostSubform[0].Page1[0].city[0]" value="city_name" />
    <Field name="topmostSubform[0].Page1[0].number[0]" value="345354" />
</Form>
<Form ID="230690" TemplateID="1123" DocType="8">
    <Field name="topmostSubform[0].Page1[0].group[0]" value="group" />
    <Field name="topmostSubform[0].Page1[0].phone[0]" value="phone" />
</Form>

我想生成4 xml它们中的每一个都由一个单一的表单节点组成。

I want to produce 4 xml's which every one of them consist of one single form node.

这是产生(每个表单节点一个):

That is produce (one for each Form node):

<Forms>
<Form ID="230688" TemplateID="1111" DocType="1">
    <Field name="topmostSubform[0].Page1[0].Street[0]" value="street" />
    <Field name="topmostSubform[0].Page1[0].HouseNo[0]" value="18" />
</Form>
</Forms>

我试过:

NodeList nodeList = (NodeList) xpath.evaluate("//Forms//Form", parser.doc,XPathConstants.NODESET);
for(int i=0; i<nodeList.getLength(); i++)
            {
                Document outputDoc = _docBuilder.newDocument();
                Element rootElement = outputDoc.createElement("Forms");
                Node childNode = nodeList.item(i);
                rootElement.appendChild(childNode);
                outputDoc.appendChild(rootElement); .....

但是这会提供一个例外:WRONG_DOCUMENT_ERR:一个节点用于不同的文件比创建它的文件要好。

But that gives an exception: "WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it."

推荐答案

你想使用 Document.importNode()


将节点从另一个文档导入到本文档,而不从原始文档更改或删除源节点;此方法创建源节点的新副本。返回的节点没有父节点; (parentNode为null)。

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node. The returned node has no parent; (parentNode is null).

这篇关于拆分xml节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆