[英]Adding and manipulating multiple child nodes using XPathNavigator in C#
我正在編寫從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到最后一個子部件似乎是完全錯誤的(盡管它可以工作)。 有一個更好的方法嗎?
我使用的另一種方法(以避免對象訪問到目前為止存儲的信息)是:
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);
}
由於這兩種方法都會產生大量開銷,因此它們似乎在某種程度上是偶然的。 我會提出任何關於如何改善算法的想法或提示。
問候,多米尼克
正如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();
}
}
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.