Home > Net >  Serialization Class to XML Problem List<>
Serialization Class to XML Problem List<>

Time:12-19

I have trouble exporting my xml from class object, when I generate my XML a node nests inside one with the same name the problem will be serialized a list.

I have an object like this: Currently my object is built alone since I am only doing tests, but the idea is to first obtain an XML that generates the structure I need.

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();
}

To serialize and export my XML I use this code I use the XmlSerializer to build the XML since it is the way I found investigated in the same way if there is any other way to generate it I am open to ideas

  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();

`

The XML I get nests the property <CdtTrfTxInf> but I need both <CdtTrfTxInf> to be outside <CdtTrfTxInf> the one that is generated more. Maybe the XML is poorly structured but this is how it is requested

<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>

I need that my <CdtTrfTxInf> be like property N times. The serializer do in other CdtTrfTxInf, the correct its like this:

<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>`

How can I get that structure or what modifications should I make so that my object constructs an XML like the one I need

CodePudding user response:

Adding XmlElementAttribute to CdtTrfTxInf should do the trick.

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