[英]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.