将子元素添加到现有元素并将父节点的内容放在新子节点中

时间:2014-02-26 19:30:21

标签: java xml dom

我使用Dom和Java来解析XML文档。在我的XML中,我有一个像:

这样的元素
<P>
All records required to be maintained pursuant to these regulations shall be maintained in accordance with Commission Regulation 1.31 (
<aref type="CFR">
17 CFR
<subref part="1" psec="" sect="31" title="17" tq="N">1.31</subref>
</aref>
) and shall be made available promptly upon request to representatives of the Commission and to representatives of applicable prudential regulators.
</P>

我需要将此元素的内容放入<p> <text>的新子元素中,如下所示:

    <P>
<text> All records required to be maintained pursuant to these regulations shall be maintained in accordance with Commission Regulation 1.31 (<aref type="CFR">17 CFR <subref title="17" part="1" sect="31" psec="" tq="N">1.31</subref>
                            </aref>) and shall be made available promptly upon request to representatives of the Commission and to representatives of applicable prudential regulators.</text>
    </P>

我编写了一段代码来执行此操作(想法是迭代所有子元素,然后逐个从<p>下移到<text>下):

Element pTag = (Element) pTags.item(i); //This is to get the list of all pTags
Element textTag = doc.createElement("text");
int pTagChildIndex = 0;
NodeList pTagChildren = pTag.getChildNodes();
while(pTagChildIndex < pTagChildren.getLength()){
    textTag.appendChild(pTagChildren.item(pTagChildIndex));
    pTagChildIndex ++;
}
pTag.appendChild(textTag);

此代码没有给出我的预期。它给出了这个:

<P>
<aref type="CFR">
17 CFR
<subref part="1" psec="" sect="31" title="17" tq="N">1.31</subref>
</aref>
<text>
All records required to be maintained pursuant to these regulations shall be maintained in accordance with Commission Regulation 1.31 () and shall be made available promptly upon request to representatives of the Commission and to representatives of applicable prudential regulators.
</text>
</P>

似乎代码没有移动所有节点。如何将所有节点从<p>下移至<text>下?

1 个答案:

答案 0 :(得分:1)

最初,您的<P>元素包含两个文本节点和一个元素节点。一共三个。但是当你循环时,从<P>中删除一个元素并将其添加到<text>,将总节点减少到2,然后递增,移动另一个文本节点,但现在长度为1,你离开循环而不处理元素节点。

解决方案是将复制getLength()的节点数量保存到可以在循环中使用的变量中,并始终获取第一个元素(0),直到没有更多。您可以像这样更改代码:

int elements = pTagChildren.getLength(); // save the number of nodes in a variable

while (pTagChildIndex < elements) { // loop using the variable
    textTag.appendChild(pTagChildren.item(0)); // always move the first element
    pTagChildIndex++;
}
相关问题