是否可以将 XML 文档反序列化为 XML 文档而不是目标文件?

Is it possible to de-serialize an XML document to XML document instead to an object file?

我有两个不同版本的 XML 文件。第一个具有较少的元素,因为它是较早开发的。现在较新的版本有额外的元素。我正在创建一个应用程序来检测 xml 文档的版本 如果所选文档是版本 0(元素较少的旧版本),那么我需要添加新元素并创建一个新的 xml 版本(版本 1 ).所以对 xaml 或 xml 使用序列化器或反序列化器是最好的方法,或者还有其他方法可以完成我的任务吗?我想用新元素更新旧的 xml 文件并将它们保存为 version1.

我正在通过 xml 文档中的 运行 for 循环检查 xml 的版本,因为有一个指定 xml 版本的子属性。

如果您有一个 class 来反序列化旧版本和新版本,那应该不是问题。

首先将旧的XML反序列化为新的class的一个对象。然后你可以设置对象的新字段并将其序列化回 xml.

也许你可以试试XDocument:

  • 使用 System.Xml.Linq 命名空间
  • 加载文件XDocument doc = XDocument.Load(filePath);
  • 搜索特殊节点(你的版本节点)
var el = doc.Descendants("Version").Where(v => v.Attribute("version").Value =="0").FirstOrDefault();
if (el != null)
{
  • 更新版本属性el.SetAttributeValue("version", 1);
  • 也许您需要删除一些节点
doc.Root.Remove(); //delete all nodes
doc.Descendants("NodeName").ToList().ForEach(xe => xe.Remove()); //delete nodename equals NodeName nodes
  • 添加节点
doc.Add(new XElement("...", new XAttribute("ID", 1)));//if you delete all nodes,you need add a root node
doc.Root.Add(new XElement("...", new XAttribute("ID", 1))); //add nodes
doc.Root.Element("...").Add(new XElement("...", new XAttribute("ID", 2)));  ////add nodes
  • 保存文件
doc.Save(filePath);
}