문제

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>
도움이 되었습니까?

해결책

  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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top