tags:

views:

40

answers:

1

I've got an xml document that filled with people (parent node is "students", and there are 25+ "student" nodes).

Each student looks like this:

<student>
  <name></name>
  <surname></surname>
  <grades>
    <subject name="">
      <small_grades></small_grades>
      <final_grade></final_grade>
    </subject>
    <subject name="">
      <small_grades></small_grades>
      <final_grade></final_grade>
    </subject>
  </grades>
  <average></average>
</student>

Basically, what I want to do ('ve been asked to do) is to make a program that would get 3 students with the best average. While parsing the document and getting three best students isn't too difficult, the XML generation is a pain in the ass.

Right now, what I'm doing is getting every single node from student and recreating it to a new file. Is there a way to copy the whole student node with everything that's in it?

Regards, Paul

+2  A: 

If using org.w3c.dom, you can use Document.importNode(Element, true) to copy subtrees.

i.e. element.appendChild(element.getOwnerDocument().importNode(student, true))

Same for dom4j, actually (and that's what you need to be using in 2010).

alamar
well, that sound good, but how would I go about finding the right `student` to import (after I've got a list of those top three)
PawelMysior
Well, for (Element student : students) root.appendChild(root.getOwnerDocument().importNode(student, true));
alamar