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);
}
どちらのアプローチも、多くのオーバーヘッドが発生するため、状況に応じたものに見えます。アルゴリズムを改善する方法についてのアイデアやヒントをいただければ幸いです。
挨拶、ドミニク