如何在 XML 序列化后没有列表元素的包装器元素
How to NOT have a wrapper element for list elements after XML serialization
我有一个classPayment
。 class 结构如下所示:
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
只需将您的贷款定义为 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; }
}
我有一个classPayment
。 class 结构如下所示:
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
只需将您的贷款定义为 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; }
}