在 C# 中反序列化 XML 时如何获取对父对象的引用?

发布于 2024-07-14 21:32:58 字数 263 浏览 3 评论 0原文

我似乎无法让它工作,这是我的(精简的)代码: -

[XmlRoot("report")]
public class Report
{
    [XmlArray("sections"), XmlArrayItem("section")]
    public List<Section> Sections;
}

public class Section
{
    public Report Report;
}

我错过了什么吗?

I can't seem to get this working, here is my (stripped down) code: -

[XmlRoot("report")]
public class Report
{
    [XmlArray("sections"), XmlArrayItem("section")]
    public List<Section> Sections;
}

public class Section
{
    public Report Report;
}

Am I missing something?

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

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

发布评论

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

评论(3

蘑菇王子 2024-07-21 21:32:58

您的对象包含 XmlSerializer 不支持的循环引用 类。 您可以改为查看 DataContractSerializer 支持此类方案。

Your objects contain circular references which is not supported by the XmlSerializer class. You could instead look at the DataContractSerializer which supports such scenarios.

靑春怀旧 2024-07-21 21:32:58

您应该确保您知道如何序列化和反序列化这些类。 编写您想要的 XML 结果,并弄清楚您希望对象如何成为 XML,反之亦然。 这不是理所当然的事。

You should make sure you know how you want those classes to serialize and deserialize. Write the XML you want as a result, and figure out how you want objects to become XML and vice versa. It's not a no-brainer.

赢得她心 2024-07-21 21:32:58

这是我的解决方案。 它可能不像你想象的那么优雅:

public class Report
{
  //...


  void PostLoad()
  {
    foreach(Section s in Sections)
    {
      s.Report = this;
    }
  }

  public static Report Load(string filename)
  {
    // Load using an XmlSerializer
    Report report = ...;

    report.PostLoad();

    return report;
  }
}

Here's my solution. It might not be as elegant as you'd expect:

public class Report
{
  //...


  void PostLoad()
  {
    foreach(Section s in Sections)
    {
      s.Report = this;
    }
  }

  public static Report Load(string filename)
  {
    // Load using an XmlSerializer
    Report report = ...;

    report.PostLoad();

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