使用 c# 从 xsd 文件生成带有子节点的 XML 文件

Generate XML file with subnodes from xsd file using c#

我有一个 xsd 文件 acount.xsd,我使用它创建了一个 acount.cs 文件,我使用它创建了一个 xml 文件。我在 c# 中编写了以下命令,用于单击按钮生成 xml 文件。

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

输出 XML 文件为:

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

我需要一个 xml 文件同时有子文件 类,比如 输出 XML 文件应为:

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

为了实现它,我尝试了以下 C# 命令,但出现错误(已指定)如何实现上述结果?

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

试试这个:

data.SalesInvoice = new [] { sales };

如错误消息所述,您需要提供一组 SalesInvoice 对象。