Question

How can I iterate through a list of xml nodes (tag="items"), and while doing so, inserting a new node in a particular place, in this case when a chileNode value changes (tag="rowNum")? Here's an example showing my input and my desired output:

Starting xml:

<items>
  <item>
     <rowNum>1</rowNum>
     <description>some text</description>
  </item>
  <item>
     <rowNum>1</rowNum>
     <description>some more text</description>
  </item>
  <item>
     <rowNum>2</rowNum>
     <description>some text</description>
  </item>
</items>

Desired output:

<items>
  <item>
     <rowNum>1</rowNum>
     <description>some text</description>
  </item>
  <item>
     <rowNum>1</rowNum>
     <description>some more text</description>
  </item>
  <item>
     <rowNum>1</rowNum>
     <description>last row 1 item</description>
  </item>
  <item>
     <rowNum>2</rowNum>
     <description>some text</description>
  </item>
  <item>
     <rowNum>2</rowNum>
     <description>last row 2 item</description>
  </item>
</items>
Was it helpful?

Solution

  1. create a variable for the rownum with an initial value set to e.g. -1
  2. loop over the item-elements, but start at the end
  3. check if the variable-value is different from the content of the rowNum-element. When yes, set the variable-value to the content of the rowNum-element and insert the new node before the nextSibling of the current item-element

Demo: http://jsfiddle.net/doktormolle/n5wUC/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top