views:

41

answers:

1

Hello,

I'm writing classes which (de)serialize to/from XML. When serializing and deserializing, the class gets a XPathNavigator to get data from/add data to.

Because the class may contain objects which are need to be serialized too (using the same mechanism), I do the following to add a child element for each object:

public void Serialize(XPathNavigator navigator)
{

    foreach(IXmlSerializableObject o in objects) {

        // Create child element.
        navigator.AppendChildElement(string.Empty, "child", string.Empty, null);

        // Move to last child element.
        navigator.MoveToChild(XPathNodeType.Element);
        while (navigator.MoveToNext(XPathNodeType.Element)) ;

        // Serialize the object at the current node.
        // This will add attributes and child elements as required.
        // The navigator will be positiononed at the same node after the call.
        o.Serialize(navigator);

        navigator.MoveToParent();
    }

}

Especially the MoveToParent/Move to last child part seems to be awfully wrong (though it works). Is there a better way to do this?

Another approach I use (to avoid that objects get access to information stored so far) is this:

foreach(IXmlSerializableObject o in objects) {
{

    // Create a new (empty) document for object serialization.
    XPathNavigator instructionNavigator = new XmlDocument().CreateNavigator();
    instructionNavigator.AppendChildElement(string.Empty, "child", string.Empty, null);
    instructionNavigator.MoveToChild(XPathNodeType.Element);

    // Serialize the object.
    o.Serialize(instructionNavigator);

    // Now add the serialized content to the navigator.
    instructionNavigator.MoveToRoot();
    instructionNavigator.MoveToChild(XPathNodeType.Element);
    navigator.AppendChild(instructionNavigator);
}

Both approaches seem to be somehow circumstantial as they both create lots of overhead. I would appriciate any ideas or hints on how to improve my algorithm.

greetings, Dominik

A: 

As Jon Skeet suggested in his comment, I now use XmlReader and XmlWriter instead of XPathNavigator. This seems much cleaner;

public void Serialize(XmlWriter writer)
{

    foreach (Instruction task in this.Tasks)
    {
        writer.WriteStartElement(task.Tag);

        task.Serialize(writer);

        writer.WriteEndElement();
    }
}

Thanks!

Korexio