Xml – What’s the best way to represent a tree with XML

data structurestreexml

I'm implementing some classes to handle the common data structures (Tree, BinaryTree, Search Binary Tree, BTree, AVL, etc). I'd like a way to store tree information in a data source and parse it to one of those classes. The simplest way is to use XML (portability is very important). The thing is that the XML documents that i make are not easy to read. They're not enough "intuitive". For example, i was doing something like this:

<?xml version="1.0" encoding="UTF-8"?>
<tree>
    <root>100</root>
    <node>
        <tree>
            <root>50</root>     
        </tree>
    </node>
    <node>
        <tree>
            <root>200</root>        
        </tree>
    </node>
</tree>

There, the tree would be something like this:

                    100
              50                200

What do you say? Do you have any other recommendation?

Best Answer

I don't see in your description any important structural difference between the root, leaves of the tree, and other nodes. So they could all have the same content model, as in this example:

<tree>
    <value>100</value>
    <tree>
        <value>50</value>
    </tree>
    <tree>
        <value>200</value>
    </tree>
</tree>

This structure is a bit less verbose, and the XML document tree is matching the tree you are trying to represent. If your values can be expressed as strings, you could even write it like that:

<tree>
    100
    <tree>50</tree>
    <tree>200</tree>
</tree>