tags:

views:

126

answers:

3

What is the most efficient way to solve this problem: I've traversed a XML file and created the following set of linked (String) lists:

  • a > b > c
  • a > b > d
  • a > f > [i]

and now I'm trying to rebuild the XML into its original structure:

<a>
 <b>
  <c/><d/>
 </b>
 <f>i</f>
</a>

Any help would really be appreciated!

+3  A: 

You probably don't want to use Lists as a data structure for this. You might be better off creating a Node type or something similar, which can contain text and child nodes, so that you can store the data in a tree / hierarchy of nodes. Something simple like this should do the trick:

public class Node {
    private String text;
    private List<Node> children = new ArrayList<Node>();

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public List<Node> getChildren() {
        return children;
    }

}

It should then be trivial to create a tree of these Nodes when you read in the file, and to use the same structure to write it back out.

matt b
A: 

You'll need to store more information about the structure of the original XML. Those 3 lists don't have information on the order of child nodes, for instance.

Darron
A: 

I'd use a tree data-structure to hold the elements in the first step (like matt explains here).

And your representation is unclear to me, how do you distinguish between a tag and an element? Since i is held in the same lists as a tag but isn't a tag.

boutta