序列化类到 XML 问题列表<>



我在从类对象导出xml时遇到问题,当我生成xml时,一个节点嵌套在一个同名节点中,问题将序列化为列表。

我有一个这样的对象:目前,我的对象是单独构建的,因为我只是在做测试,但我的想法是首先获得一个生成所需结构的XML。

public class PmtInf
{
public string PmtInfId = "PAYMENT REFERENCE";//Referencia de pago
public string PmtMtd = "TRF";
public PmtTpInf PmtTpInf = new PmtTpInf();
public string ReqdExctnDt = "2020-06-24";//Fecha de pago
public Dbtr Dbtr = new Dbtr();
public InitgPty DbtrAcct = new InitgPty();
//Problem this Property
public List<CdtTrfTxInf> CdtTrfTxInf = new List<CdtTrfTxInf>() { new CdtTrfTxInf(), new        CdtTrfTxInf() };
}
public class CdtTrfTxInf
{
public PmtId PmtId = new PmtId();
public Amt Amt = new Amt();
public CdtrAgt CdtrAgt = new CdtrAgt();
public Dbtr Cdtr = new Dbtr();
public InitgPty CdtrAcct = new InitgPty();
}

为了序列化和导出我的XML,我使用以下代码我使用XmlSerializer来构建XML,因为这是我发现的以相同方式进行调查的方式。如果有任何其他方式来生成它,我对的想法持开放态度

var XML = new System.Xml.Serialization.XmlSerializer(Objeto.GetType());
var Path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)"//XMLExport.xml";
FileStream file = File.Create(Path);
XML.Serialize(file, Objeto);
file.Close();

`

我得到的XML嵌套属性<CdtTrfTxInf>,但我需要两个<CdtTrfTxInf>都在生成更多的<CdtTrfTxInf>之外。也许XML的结构很差,但就是这样请求的

<PmtInf>
<PmtInfId>PAYMENT REFERENCE</PmtInfId>
<PmtMtd>TRF</PmtMtd>
<PmtTpInf>
</PmtTpInf>
<ReqdExctnDt>2020-06-24</ReqdExctnDt>
<Dbtr>
</Dbtr>
<DbtrAcct>
</DbtrAcct>
<!-- Here its the problem my node CdtTrfTxInf its un other CdtTrfTxInf -->
<CdtTrfTxInf>
<CdtTrfTxInf>
more....
</CdtTrfTxInf>
<CdtTrfTxInf>
more....
</CdtTrfTxInf>
</CdtTrfTxInf>
</PmtInf>

我需要我的<CdtTrfTxInf>像属性一样N次。串行器在其他CdtTrfTxInf中做,正确的做法如下:

<PmtInf>
<PmtInfId>PAYMENT REFERENCE</PmtInfId>
<PmtMtd>TRF</PmtMtd>
<PmtTpInf>
</PmtTpInf>
<ReqdExctnDt>2020-06-24</ReqdExctnDt>
<Dbtr>
</Dbtr>
<DbtrAcct>
</DbtrAcct>
<CdtTrfTxInf>
more....
</CdtTrfTxInf>
<CdtTrfTxInf>
more....
</CdtTrfTxInf>
</PmtInf>`

我如何获得该结构,或者我应该做什么修改,以便我的对象构建一个像我需要的一样的XML

XmlElementAttribute添加到CdtTrfTxInf就可以了。

public class PmtInf
{
...
[XmlElement] // Add this attribute
public List<CdtTrfTxInf> CdtTrfTxInf = ...
}

最新更新