我正在编写对 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);
}
这两种方法似乎都是间接的,因为它们都会产生大量开销。我会就如何改进我的算法提出任何想法或提示。
问候,多米尼克