gpt4 book ai didi

java - 使用 XOM 插入附加父 XML 元素

转载 作者:太空宇宙 更新时间:2023-11-04 08:20:06 25 4
gpt4 key购买 nike

使用以下 XML:

<parent>
<child>Stuff</child>
<child>Stuff</child>
</parent>

使用 XPath 我查询子元素,并根据某些条件我想在其中一些元素之上附加一个额外的父级别:

<parent>
<extraParent>
<child>Stuff</child>
</extraParent>
<child>Stuff</child>
</parent>

最好的方法是什么?

我的想法如下:

Nodes childNodes = parent.query("child");
for (int i = 0; i < childNodes.size(); i++) {
Element currentChild = (Element) childNodes.get(i);
if (someCondition) {
ParentNode parent = currentChild.getParent();
currentChild.detach();
Element extraParent = new Element("extraParent");
extraParent.appendChild(currentChild);
parent.appendChild(extraParent);
}
}

但我想保留顺序。也许可以使用parent.insertChild(child,position)来完成?

编辑:我认为以下方法有效,但我很好奇是否有人有更好的方法:

Elements childElements = parent.getChildElements();
for (int i = 0; i < childElements.size(); i++) {
Element currentChild = childElements.get(i);
if (someCondition) {
ParentNode parent = currentChild.getParent();
currentChild.detach();
Element extraParent = new Element("extraParent");
extraParent.appendChild(currentChild);
parent.insertChild(extraParent,i);
}
}

编辑 2:这可能更好,因为它允许您将其他元素与您不感兴趣的子元素混合在一起:

Nodes childNodes = parent.query("child");
for (int i = 0; i < childNodes.size(); i++) {
Element currentChild = (Element) childNodes.get(i);
if (someCondition) {
ParentNode parent = currentChild.getParent();
int currentIndex = parent.indexOf(currentChild);
currentChild.detach();
Element extraParent = new Element("extraParent");
extraParent.appendChild(currentChild);
parent.insertChild(extraParent,currentIndex);
}
}

最佳答案

这似乎足够有效:

Nodes childNodes = parent.query("child");
for (int i = 0; i < childNodes.size(); i++) {
Element currentChild = (Element) childNodes.get(i);
if (someCondition) {
ParentNode parent = currentChild.getParent();
int currentIndex = parent.indexOf(currentChild);
currentChild.detach();
Element extraParent = new Element("extraParent");
extraParent.appendChild(currentChild);
parent.insertChild(extraParent,currentIndex);
}
}

关于java - 使用 XOM 插入附加父 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9718973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com