开发者

Java duplicating xml node and child nodes with replace

开发者 https://www.devze.com 2023-02-15 17:13 出处:网络
I have an XML template with nodes like (simplified): <items> <开发者_开发知识库;sl:each value=\"iter\" ignoreonzero=\"total\">

I have an XML template with nodes like (simplified):

<items>
<开发者_开发知识库;sl:each value="iter" ignoreonzero="total">
  <item>
    <description><sl:prop value="desc" /></description>
    <total><sl:prop value="total" /></description>
  </item>
</sl:each>
</items>

I can get the iterator (an ArrayList) and get the values of the object. I just can't figure out how to use this entire node as a template (except the <sl:each> wrapper), keeping it's children (and their children recursive) intact. I need to replace the <sl:prop /> nodes with the value from the object in the ArrayList, reapeated for each item.

Sample Desired output:

<items>
  <item>    
    <description>item 1</description>
    <total>1.23</description>
  </item>
  <item>    
    <description>item 2</description>
    <total>3.21</description>
  </item>
</items>  

What I've been trying: Any help please?

import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;


NodeList eaches = itemsElement.getElementsByTagNameNS("sl","each");
for (int i=0;i<eaches.getLength();i++) 
{
  Node origNode = eaches.item(i);
  /*
    Code to get ArrayList and object
  */
  for (Object o : iter) {
    Node node = origNode.cloneNode(true);
    NodeList props = ((Element) node).getElementsByTagNameNS("sl","prop");
    for (int j=0;j<props.getLength();j++) {
      Node prop = props.item(j);
      String textContent = "";
      /*
        Code to get text content
      */
      Node parent = prop.getParentNode();
      Node text = doc.createTextNode(textContent);
      parent.replaceChild(prop,text);
    }
  }
}


After calling Node node = origNode.cloneNode(true); you should call insertAfter on eaches parent node. Don't forget to remove the eaches node after the iteration!

0

精彩评论

暂无评论...
验证码 换一张
取 消