维护 XmlSerializer 生成的对象中的 xml 层次结构(即父子)信息

发布于 2024-08-12 18:18:10 字数 489 浏览 1 评论 0原文

一段时间以来,我一直在尝试解决以下问题,但我开始没有想法了:

我已经使用 xsd.exe 工具从 xsd 模式生成了一组 C# 类,并且反序列化 xml 文件工作正常。问题是,除了使用自动生成的类的方便和安全之外,我还需要有关xml层次结构的信息,即我需要在反序列化期间创建的对象之间建立父子关系。请注意,我想避免保留单独的 xml 层次结构(如 DOM 树),而是让生成的对象跟踪其父对象和子对象。

我已经成功地使用 JAXB 在 java 中实现了这一点,方法是:

  1. 为所有反序列化对象定义一个公共基类。该基类包含子对象列表和对父对象(如果有)的引用。

  2. 使用 Unmarshaller.Listener 功能提供已完成的对象反序列化的回调。此回调提供对最近反序列化对象的父级的引用,这使得建立父子关系变得微不足道。

我将如何在 C# 中做到这一点?我查看了 MSDN 文档并进行了大量的谷歌搜索,但未能找到任何有用的信息。

for some time now I have been trying to solve the following problem and I'm starting to run out of ideas:

I have generated a set of C# classes from an xsd schema using the xsd.exe tool and deserializing xml files works fine. The problem is that apart from the convenience and safety of using the auto generated classes, I also need information about the xml hierarchy, ie I need to establish parent-child relationships between the objects created during deserialization. Note that I want to avoid keeping a separate xml hierarchy structure (like a DOM tree), but rather make the generated objects keep track of their parents and children.

I have managed to pull this off in java using JAXB by:

  1. Defining a common base class for all deserialized objects. This base class contains a list of children and a reference to a parent object (if any).

  2. Using the Unmarshaller.Listener functionality that provides a callback on completed object deserialization. This callback provides a reference to the parent of the recently deserialized object, which makes establishing parent-child relationships trivial.

How would I go about doing this in C#? I have had a look at the MSDN docs and done quite a lot of googling, but haven't been able to find any useful information.

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

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

发布评论

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

评论(2

葬シ愛 2024-08-19 18:18:10

我前段时间写过一篇关于这个问题的文章,也许对你有帮助。

http://www.thomaslevesque.com/ 2009/06/12/c-parentchild-relationship-and-xml-序列化/

I wrote an article some time ago about this exact problem, perhaps it can help you.

http://www.thomaslevesque.com/2009/06/12/c-parentchild-relationship-and-xml-serialization/

风筝有风,海豚有海 2024-08-19 18:18:10

XmlSerializer 应维护简单的对象层次结构以进行序列化和反序列化。复杂的事物(例如包含不止一种类型的对象的数组或列表)有点棘手。 。 。但有可能。

XmlSerializer should maintain simple object hierarchies for serialization and deserialization. Complex things such as arrays or lists containing more than one type of object are a bit tricker. . . but possible.

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