简体   繁体   中英

Generate XML file with subnodes from xsd file using c#

I have a xsd file acount.xsd, using which i created a acount.cs file, using this i created a xml file. I have written these following command in c# for button click to generate the xml file.

string PATH = "C:\\Sample.xml";
CreateEmptyFile(PATH);
var data = new AutoCount();
data.Product = "AutoCount Accounting";
data.Version = "1.5";
data.CreatedApplication = "BApp";
data.CreatedBy = "Business Solutions";
data.CreatedDateTime = DateTime.Now;

var serializer = new XmlSerializer(typeof(AutoCount));
using (var stream = new StreamWriter(PATH))
    serializer.Serialize(stream, data);

Output XML file was :

<?xml version="1.0" encoding="utf-8"?>
<AutoCount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.autocountsoft.com/ac_accounting.xsd">
  <Product>AutoCount Accounting</Product>
  <Version>1.5</Version>
  <CreatedApplication>BApp</CreatedApplication>
  <CreatedBy>Business Solutions</CreatedBy>
</AutoCount>           

I need a xml file while has sub classes, like Output XML file should be:

<?xml version="1.0" encoding="utf-8"?>
<AutoCount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.autocountsoft.com/ac_accounting.xsd">
  <Product>AutoCount Accounting</Product>
  <Version>1.5</Version>
  <CreatedApplication>BApp</CreatedApplication>
  <CreatedBy>Business Solutions</CreatedBy>
  <Sales DocNo = 'S0001'>
    <Item>XXX</Item>
    <Qty>2</Qty>
    <Price>6.00</Price>
  </Sales>
</AutoCount> 

To Achieve it i tried this following C# command, but error occurs (have specified it) How do i achieve the above result?

string PATH = "C:\\Sample.xml";
CreateEmptyFile(PATH);
var sales = new SalesInvoice();
sales.DocNo = "S0001";
sales.Item = "XXX";
sales.Qty= "2";
sales.Price= "6.00";
var data = new AutoCount();
data.Product = "AutoCount Accounting";
data.Version = "1.5";
data.CreatedApplication = "BApp";
data.CreatedBy = "Business Solutions";
data.CreatedDateTime = DateTime.Now;
data.SalesInvoice = sales; /*Error:  Cannot implicitly convert SalesInvoice to SalesInvoice[] */
var serializer = new XmlSerializer(typeof(AutoCount));
using (var stream = new StreamWriter(PATH))
    serializer.Serialize(stream, data);

Try this:

data.SalesInvoice = new [] { sales };

As the error message states you need to provide an array of SalesInvoice objects.

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