c# - 如何在 XML 序列化后没有列表元素的包装器元素

标签 c# .net xml serialization xml-serialization

<分区>

我有一个类 Payment。类结构如下所示:

public class Payment
{
  public decimal Amount{get;set;}
  public List<Loan> Loans{get;set;}
}
public class Loan
{
  public decimal Debt{get;set;}
  public string Lender{get;set;}
}

当我将其序列化为 XML 时,默认情况下它会生成如下内容:

<Payment>
  <Amount>...</Amount>
  <Loans>
    <Loan>...</Loan>
    <Loan>...</Loan>
  </Loans>
</Payment>

但我想要这样的输出:

<Payment>
  <Amount>...</Amount>
  <Loan>...</Loan>
  <Loan>...</Loan>
</Payment>

我怎样才能达到我想要的输出?

我的 XML 序列化代码是这样的:

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Payment));

StringBuilder sb = new StringBuilder();
using (System.IO.TextWriter writer = new System.IO.StringWriter(sb))
{                    
  serializer.Serialize(writer, mainDocument);
  writer.Flush();
}
finalXML = sb.ToString();
// finalXML contains the XML string

最佳答案

只需将您的 Loans 定义为 XmlElement:

public class Payment
{
    public decimal Amount { get; set; }
    [XmlElement("Loan")] 
    public List<Loan> Loans { get; set; }
}
public class Loan
{
    public decimal Debt { get; set; }
    public string Lender { get; set; }
}

关于c# - 如何在 XML 序列化后没有列表元素的包装器元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57505241/

相关文章:

c# - 如何在不在 C# Windows 应用程序中创建父类的新实例的情况下返回父窗体

java - 在 MVC 框架中捕获异常的位置

xml - XSL :copy-of How to copy some attributes from a node?

安卓 : Cdata in xml not parsing correctly(sax)

c# - 使用 COM 将数组从 C# 返回到经典 ASP

c# - 如何将项目添加到已在源代码管理中的解决方案中?

C# 项目文件夹命名约定

c# - LINQ to Entities 在尝试解析列以进行不等式比较时无法识别方法 'Int32 Parse(System.String)' 方法

c# - 检测 PowerPoint 幻灯片是否隐藏

java - 使用 xsl java 将 xml 转换为 csv