2012-03-15 2 views
1

Со следующим XML:Вставьте дополнительный родительский XML-элемент с помощью XOM

<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)?

Edit: Я думаю, что следующие работы, но мне интересно, если у кого есть лучший способ:

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

Edit 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); 
    } 
} 

ответ

1

Это, кажется, работает адекватно:

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); 
    } 
} 
Смежные вопросы