简体   繁体   中英

How to populate XML object with data, based on XSD

I need to export data into XML file, using XSD. There are many examples how to do it, but most of them do not show how to popuate the actual data, but to save the object as an XML. The one I could find didn't work for me.

1) I use an xsd file of Agresso http://services.agresso.com/schema/ABWInvoice/2011/11/14/ABWInvoice.html which I have successfully downloaded and generated a class with xsd.exe command.

2) I have added this class to my project. ABWInvoice is the class for the the complexType element Invoice. The xml may contain more than one invoice, hence its maxOccurs is set to "unbounded". Each Invoice can have InvoiceNo element and Header complex element.

3) I have started to write the code and first thought I can use a list, as number of invoices is dynamic. But List<ABWInvoice> list = new ABWInvoice(); didn't work "Cannot implicitly convert type 'abc.Agresso.ABWInvoice' to 'System.Collections.Generic.List'", so I have decided to at least try to have one record and go from there, but oAgresso.Invoice[0].Header fails in runtime with System.NullReferenceException: 'Object reference not set to an instance of an object.'

 private void CreateXMLHeader()
    {
        var oAgresso = new ABWInvoice { };

        oAgresso.Invoice[0] = new ABWInvoiceInvoice
        { InvoiceNo = "1" };
        oAgresso.Invoice[0].Header = new ABWInvoiceInvoiceHeader()
        {
            OrderRef = "5678",
            InvoiceDate = Date.Now
        };




        //var agressoXMLImport = Shared.XMLHelper.ReadXml<ABWInvoice>(@"E:\temp\ABW_Invoice_Test.xml");
        Shared.XMLHelper.SaveXml<ABWInvoice>(oAgresso, @"e:\temp\ABW_Export_Test.xml");

    }

Can you advise on how 1) build a dynamic array (I do not know the amount of invoices, when I start building the XML; 2)What is wrong with my current code?

Much appreciated!

Member arrays need to be initialized with known size, so its easier to make a List of ABWInvoiceInvoice then populate it with your data by using add method and at the end assign whole list to your member array

private void CreateXMLHeader()
    {
        var oAgresso = new ABWInvoice { };
        List<ABWInvoiceInvoice> invlist = new List<ABWInvoiceInvoice>();
        invlist.Add(new ABWInvoiceInvoice { InvoiceNo = "1" ,
        Header= new ABWInvoiceInvoiceHeader()
        {
            OrderRef = "5678",
            InvoiceDate = DateTime.Now
        }
        });
        oAgresso.Invoice = invlist.ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM