1

我正在编写对 XML 进行(反)序列化的类。在序列化和反序列化时,该类获取一个 XPathNavigator 以从中获取数据/向其中添加数据。

因为该类可能包含也需要序列化的对象(使用相同的机制),所以我执行以下操作来为每个对象添加一个子元素:

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();
    }

}

特别是 MoveToParent/Move to last child 部分似乎非常错误(尽管它有效)。有一个更好的方法吗?

我使用的另一种方法(以避免对象访问到目前为止存储的信息)是:

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);
}

这两种方法似乎都是间接的,因为它们都会产生大量开销。我会就如何改进我的算法提出任何想法或提示。

问候,多米尼克

4

1 回答 1

0

正如 Jon Skeet 在他的评论中建议的那样,我现在使用 XmlReader 和 XmlWriter 而不是 XPathNavigator。这看起来更干净;

public void Serialize(XmlWriter writer)
{

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

        task.Serialize(writer);

        writer.WriteEndElement();
    }
}

谢谢!

于 2010-10-15T10:51:37.030 回答