簡體   English   中英

使用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文件,例如Output XML file應該是:

<?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對象數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM