0

E.g.

tree:

    A
A1     A2

serialize to an xml:

<A> <A1> </A1> <A2> </A2> </A>

It seems either root-first traversal (preorder) or root-last traversal (postorder) is not enough to achieve this.

What is the good way to do this?

JackWM
  • 10,085
  • 22
  • 65
  • 92

1 Answers1

1

The answer mostly depends on how you define "good".

Neither preorder nor postorder is really good. When strictly applied they require the root to be completely processed before/after the children are processed. In this interpretation both require you to build the string in memory, e.g. (postorder):

function process(item)
{
    text=""
    foreach(child in children)
        text=text+process(child)
    return startTag(item)+text+endTag(item)
}

A better solution is streamable:

function process(item,stream)
{
    startTag(item,stream)
    foreach(child in children)
        process(child,stream)
    write endTag(item,stream)
}

Here startTag and endTag do not return the string, but write its parts to the stream as soon as possible.

Levente Pánczél
  • 1,895
  • 2
  • 14
  • 16