0

I have a scenario where I need to get the sub pages inside a book (max 3) and move those pages to parent of book.

Like:

<book>
 <book1>
   <page1>
   <page2>
   <page3>
   <page4>
 </book1> 
</book>

So, if number of pages under book1 are greater than 3, split the book1 into 2 namely book1_h_1 and book2_h_2 and move page1, page2, page under book1_h_1 and move page4 under book1_h_2. There can be a scenario of more than 4 pages under book1 like 10 or more.

In order to get how many new books needs to be created I did the following

List<Element> elChildren = book1.getChildren();
int size = 3;
int numBatches = (elChildren.size() / size) + 1;
List<Element> batches = null;
for (int index = 0; index < numBatches; index++) {
int count = index + 1;
int fromIndex = Math.max(((count - 1) * size), 0);
int toIndex = Math.min((count * size), elChildren.size());
batches = elChildren.subList(fromIndex, toIndex);
}

public static void createElementNew(Element parent, int i){
for(int q = 1; q <=i; q++){
parent.addContent(new Element("book1_h_"+q));
}
}

My Question is how can I add list "batches" to newly created books "book1_h_1 and book1_h_2?

Can someone help me on this?

Tarun
  • 35
  • 1
  • 1
  • 6

1 Answers1

0

You can do the whole thing with one iterator..... No need to keep things in variables and lists of buckets.

'booke' will point to the book1 element...

Element booke = ..... ;
Element parent = booke.getParentElement();
int bookpos = parent.indexOf(booke);
Iterator<Element> lit = booke.getChildren().iterator();

int cnt = 0;
int bkh = 1;
Element bke = null;
String namebase = booke.getName() + "_h_";
while (it.hasNext()) {
    Element page = it.next();
    if (cnt >= 3) {
       if ((cnt % 3) == 0) {
          bkh++;
          bookpos++;
          bke = new Element(namebase + bkh);
          parent.addContent(bookpos, bke);
       }
       it.remove();
       bke.add(page);
    }
    cnt++;
}
if (cnt > 3) {
    booke.setName(namebase + "1");
}

Rolfl

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • Hi Rolfl, Can you please help me with this issue? http://stackoverflow.com/q/15627183/1634388 – Tarun Mar 26 '13 at 10:59