【发布时间】:2021-07-17 00:52:03
【问题描述】:
这可能很简单,但对于我的一生,我一直无法弄清楚。我是架构的新手,所以这绝对是我的问题的一部分。
我有一个 C# 程序,它从数据库中提取表并将这些表添加到数据表,然后添加到数据集。从那里,我使用 WriteXml(fileName) 来生成 XML。我已经能够从生成的 XML 创建 XSD,然后根据我希望 XML 输出的外观进行一些更改。
如何使用我创建的自定义 XSD 来正确格式化 XML?非常感谢任何图书馆或任何形式的建议。
以下是我用来编写 xml 的代码。
public static void WriteXml(string filePath, string projectType)
{
List<string> tableNames = GetAllTableNames();
try
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
SqlConnection con;
SqlDataAdapter sda;
DataTable dt;
DataSet ds = new DataSet(projectType);
using (con = new SqlConnection(connectionString))
{
con.Open();
foreach (string table in tableNames)
{
using (var cmd_selectAllFromTable = new SqlCommand())
{
cmd_selectAllFromTable.Connection = con;
cmd_selectAllFromTable.CommandType = CommandType.Text;
cmd_selectAllFromTable.CommandText = "SELECT * FROM " + table;
dt = new DataTable(table);
sda = new SqlDataAdapter(cmd_selectAllFromTable);
sda.Fill(dt);
ds.Tables.Add(dt);
}
}
con.Close();
}
ds.WriteXml(filePath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
下面是架构。我已经包含了第一个元素的外观,然后会有更多元素。我想要的是我生成的 XML 遵循 XSD(如下)并按我想要的顺序创建元素。
<?xml version="1.0" encoding="Windows-1252"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Program">
<xs:complexType>
<xs:sequence>
<xs:element name="Project">
<xs:complexType>
<xs:sequence>
<xs:element name="Id" type="xs:string" />
<xs:element name="Name" type="xs:string" />
<xs:element name="Field1" type="xs:string" />
<xs:element name="Field2" type="xs:string" />
<xs:element name="Field3" type="xs:dateTime" />
<xs:element name="Field4" type="xs:string" />
<xs:element name="Field5" type="xs:string" />
<xs:element name="Field6" type="xs:string" />
<xs:element name="Field7" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
【问题讨论】: