0

Oh boy They ust be tired of me now.

My trouble: I have two ArrayLists of custom classes.

ArrayList<Subject>` **a**`ArrayList<Student>**b**

Within those custom classes are other custom classes which themselves have primitive data types as well as an ArrayList of other custom classes. It's a big circus going on.

How do I XMLEncode those two ArrayLists, a and b, so that all the information within them branching all the way down, is saved?
(Also, is it possible to save both of these to the same file please?)

3
Contributors
4
Replies
26
Views
3 Years
Discussion Span
Last Post by JamesCherrill
Featured Replies
  • 1

    sure, why not? if for each class you write a method that returns the xml code it should represent, for instance, and call that from within the main class. http://docs.oracle.com/javase/tutorial/jaxp/xslt/writingDom.html as for you question of the same file: sure, if you code it that way. Read More

  • Use java.beans.XMLEncoder and pass it the ArrayList. It will encode the entire ArrayList and it's constituent classes and their ArrayLists of other classes and primitives all the way down. Your custom classes just need to comply with JavaBeans standards (get/set/add methods, a no-args constructor). It encodes to a Stream so … Read More

  • That's the solution I proposed earlier, except that he misses a key point - which is that ArrayLists can also be encoded/decoded (the ArryaList class has been retrofitted with extra methods to support XML encoding). He messes about writing the arraylist elements one at a time, then reading them back … Read More

1

Use java.beans.XMLEncoder and pass it the ArrayList. It will encode the entire ArrayList and it's constituent classes and their ArrayLists of other classes and primitives all the way down.
Your custom classes just need to comply with JavaBeans standards (get/set/add methods, a no-args constructor).
It encodes to a Stream so you can do multiple encodes and subsequent decodes on the same stream/file.

I have a little demo using an ArrayList of instances of a class that contains another ArrayList among its instance variables, should you need convincing...

Edited by JamesCherrill

1

That's the solution I proposed earlier, except that he misses a key point - which is that ArrayLists can also be encoded/decoded (the ArryaList class has been retrofitted with extra methods to support XML encoding). He messes about writing the arraylist elements one at a time, then reading them back in and addig them to a new list. All you need is to encode the ArrayList itself (one call) and decode it (one call)

Votes + Comments
:D Thank you.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.