JackWM
JackWM

Reputation: 10545

What is the algorithm for serializing the DOM to an XML text file?

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?

Upvotes: 0

Views: 135

Answers (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.

Upvotes: 1

Related Questions