我可以在不破坏向后兼容性的情况下向列表成员添加 [XmlElement] 属性吗?

发布于 2024-12-29 22:59:03 字数 746 浏览 3 评论 0原文

我相信以下内容:

public List<Vector3> Vectors;

将序列化为:

<Vectors>
 <Vector3>
  <X>0</X>
  <Y>0</Y>
  <Z>0</Z>
 </Vector3>
</Vectors>

我想删除封装标签,我相信我可以这样做:

[XmlElement("Vector3")]
public List<Vector3> Vectors;

应该序列化为:

 <Vector3>
  <X>0</X>
  <Y>0</Y>
  <Z>0</Z>
 </Vector3>

但我担心这会破坏仍在使用“向量”的旧 XML 文件列表周围的标记。有没有通用的方法来解决这个问题?

编辑:上面的列表将是容器对象的一部分,因此完整的 XML 可能以以下开头

<Container>

和结尾:

</Container>

我最初将其省略,以缩短问题的长度。

I believe the following:

public List<Vector3> Vectors;

Will serialize out to:

<Vectors>
 <Vector3>
  <X>0</X>
  <Y>0</Y>
  <Z>0</Z>
 </Vector3>
</Vectors>

I want to remove the encasing tag which I believe I can do like this:

[XmlElement("Vector3")]
public List<Vector3> Vectors;

Which should serialize to:

 <Vector3>
  <X>0</X>
  <Y>0</Y>
  <Z>0</Z>
 </Vector3>

But I'm afraid that would break old XML files that are still using the "Vectors" tag around the list. Is there a common way to solve this?

EDIT: The list above would be part of a container object, so the full XML might begin with

<Container>

and end with

</Container>

I left that out originally to keep the question shorter.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青衫儰鉨ミ守葔 2025-01-05 22:59:03

我不相信 XML 有任何内置的版本控制机制。我认为你最好的选择是编写一些外部机制,它可以检测你定义的“版本”,并手动将旧版本反序列化到新对象中。您可能还需要定义一个新版本的成员变量或属性,它将与您的对象进行序列化,以防您再次遇到相同的问题,因为一旦您第二次更改架构,您将需要担心 3 个版本。

您可以通过在对象上定义 IXmlSerialized 并定义 readXml/writeXml 函数来编写自定义反序列化方法,也可以使用某些外部进程基于旧版本生成新的 XML 格式。也许首先将 XML 文件加载到 XmlDocument 中,按照您想要的方式修复它(即将 Vector3 节点向上移动一个级别并删除 Vectors 节点),然后将文档的 OuterXml 值保存到字符串中并通过 MemoryStream 反序列化。

I don't believe XML has any sort of built in mechanism for versioning. I think your best bet is going to be writing some external mechanism which can detect the "version" as defined by you and deserialize the old version into your new object manually. You probably will also want to define a new version member variable or property which will serialize with your object in case you run into the same problem again, because once you change the schema a 2nd time, you will have 3 versions to worry about.

You can either write a custom deserialize method by defining IXmlSerializable on your object and defining the readXml/writeXml functions, or you can use some external process to generate the new XML format based on the old version. Perhaps load the XML file into an XmlDocument first, fix it how you want (i.e. move the Vector3 nodes up a level and remove the Vectors node), then save the document's OuterXml value into a string and deserialize via a MemoryStream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文