次の 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);
}
}