【问题标题】:How to generate XML file from dataset using XSD and MVC如何使用 XSD 和 MVC 从数据集生成 XML 文件
【发布时间】:2015-08-27 17:38:26
【问题描述】:

我有一个引用其他 XSD 文件的 XSD 文件。 Tomcat 应用程序使用它来生成带有水样结果的 XML 文件。 在 MVC 应用程序中,我需要查询数据库,取回行,并将它们转换为通过引用 XSD 文件格式化的 XML 文档。我现在唯一能想到的解决方案是拥有一个现有的 XML 文件并将标签放入字符串中,然后循环遍历字符串,用行的值替换标签。

.NET MVC5 中有什么可以做这样的事情吗?我难住了。 下面是一些相关的部分。

============================================

顶部的 XML 文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<EN:eDWR xmlns:EN="urn:us:net:exchangenetwork"
    xmlns:SDWIS="http://www.epa.gov/sdwis"
    xmlns:ns3="http://www.epa.gov/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <EN:Submission EN:submissionFileCreatedDate="2012-07-21"
        EN:submissionFileName="B_14271BJB.csv" EN:submissionID="1">
        <EN:LabReport>
            <EN:LabIdentification>
                <EN:LabAccreditation>
                    <EN:LabAccreditationIdentifier>OR100024</EN:LabAccreditationIdentifier>
                    <EN:LabAccreditationAuthorityName>STATE</EN:LabAccreditationAuthorityName>
                </EN:LabAccreditation>
            </EN:LabIdentification>
            <EN:Sample>
                <SDWIS:RecordID>155628</SDWIS:RecordID>
                <EN:SampleIdentification>
                    <EN:LabSampleIdentifier>123321</EN:LabSampleIdentifier>
                    <EN:PWSIdentifier>OR4100237</EN:PWSIdentifier>
                    <EN:PWSFacilityIdentifier>DIST-A</EN:PWSFacilityIdentifier>
                    <EN:SampleRuleCode>TC</EN:SampleRuleCode>
                    <EN:SampleMonitoringTypeCode>RP</EN:SampleMonitoringTypeCode>

====================================

xsd 文件完成。它引用同一文件夹中的其他 xsd 文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSPY v5 rel. 4 U (http://www.xmlspy.com) by Leslie Flagler (SAIC) -->
<xsd:schema targetNamespace="urn:us:net:exchangenetwork" xmlns:SDWIS="http://www.epa.gov/sdwis" xmlns:EN="urn:us:net:exchangenetwork" xmlns:facid="http://www.epa.gov/xml" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="qualified" version="3.0">
    <xsd:annotation>
        <xsd:documentation/>
    </xsd:annotation>
    <xsd:include schemaLocation="./EDWR_MetaData.xsd"/>
    <xsd:include schemaLocation="./EDWR_ContactPoint.xsd"/>
    <xsd:include schemaLocation="./SDWIS_LabReport.xsd"/>
    <xsd:include schemaLocation="./EDWR_Authentication.xsd"/>
    <xsd:element name="eDWR">
        <xsd:annotation>
            <xsd:documentation>This is the standard regulatory schema
                approved by the USEPA and multi-state Lab to State
                Drinking Water Integrated Project Team</xsd:documentation>
        </xsd:annotation>
        <xsd:complexType>
            <xsd:annotation>
                <xsd:documentation>This is enfoTech EDWR schema</xsd:documentation>
            </xsd:annotation>
            <xsd:sequence>
                <xsd:element ref="EN:MetaData" minOccurs="0"/>
                <xsd:element ref="EN:Receiver" minOccurs="0"/>
                <xsd:element ref="EN:Sender" minOccurs="0"/>
                <xsd:element ref="EN:Submission"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:complexType name="SubmissionDataType">
        <xsd:annotation>
            <xsd:documentation>Transction information</xsd:documentation>
        </xsd:annotation>
        <xsd:sequence>
            <xsd:element ref="EN:LabReport" minOccurs="0" maxOccurs="unbounded"/>
            <xsd:element ref="EN:SubmissionCertification" minOccurs="0"/>
        </xsd:sequence>
        <xsd:attribute name="submissionID" type="xsd:string"/>
        <xsd:attribute name="submissionFileName" type="xsd:string"/>
        <xsd:attribute name="submissionFileCreatedDate" type="xsd:date"/>
    </xsd:complexType>
    <xsd:element name="MetaData" type="EN:MetaDataDataType">
        <xsd:annotation>
            <xsd:documentation>General information about the schema</xsd:documentation>
        </xsd:annotation>
    </xsd:element>
    <xsd:element name="Receiver" type="EN:ContactPointDataType">
        <xsd:annotation>
            <xsd:documentation>Regulatory agency and contact to receive
                the e-DWR submission file</xsd:documentation>
        </xsd:annotation>
    </xsd:element>
    <xsd:element name="Sender" type="EN:ContactPointDataType">
        <xsd:annotation>
            <xsd:documentation>The sender of the e-DWR submission file</xsd:documentation>
        </xsd:annotation>
    </xsd:element>
    <xsd:element name="LabReport" type="EN:LabReportDataType">
        <xsd:annotation>
            <xsd:documentation>Lab Analysis Report (includes Lead and
                Copper Report, Water Quality Parameters, and
                Bacteriological Analysis Report, etc)</xsd:documentation>
            <xsd:documentation>Chemical Analysis Report (includes Lead
                and Copper Report, Water Quality Parameters, and
                Bacteriological Analysis Report)</xsd:documentation>
        </xsd:annotation>
    </xsd:element>
    <xsd:element name="SubmissionCertification" type="EN:AuthenticationDataType">
        <xsd:annotation>
            <xsd:documentation>Submission Certification</xsd:documentation>
        </xsd:annotation>
    </xsd:element>
    <xsd:element name="Submission" type="EN:SubmissionDataType">
        <xsd:annotation>
            <xsd:documentation>Information pertaining to a drinking
                water report submission</xsd:documentation>
        </xsd:annotation>
    </xsd:element>
</xsd:schema>

【问题讨论】:

  • 为什么在编写代码生成xml时需要模式?作为软件验证的一部分,您应该在将 xml 输出到文件之后针对架构验证 xml。它不必动态执行。在 c# 中使用 XML Linq 生成 xml 非常简单。
  • Johnv2020:不,这没有帮助。当我尝试从 .xsd 文件生成类时,命令提示符返回了大量错误。 @jdweng:是的,你可能是对的。我会吃完午饭回来,朝那个方向走,然后回到这里做出回应。

标签: c# xml xsd


【解决方案1】:

这给出了准确的结果。开始很艰难,剩下的很容易。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Linq;



namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        const string FILENAME = @"c:\temp\test.xml";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string identification =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
      "<EN:eDWR" +
      " xmlns:EN=\"urn:us:net:exchangenetwork\"" +
      " xmlns:SDWIS=\"http://www.epa.gov/sdwis\"" +
      " xmlns:ns3=\"http://www.epa.gov/xml\"" +
      " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
      "/>";

            XDocument doc = XDocument.Parse(identification);
            XElement eDWR = doc.Elements().Where(x => x.Name.LocalName == "eDWR").FirstOrDefault();

            XNamespace EN = eDWR.GetNamespaceOfPrefix("EN");
            XNamespace SDWIS = eDWR.GetNamespaceOfPrefix("SDWIS");
            XNamespace ns3 = eDWR.GetNamespaceOfPrefix("ns3");
            XNamespace xsi = eDWR.GetNamespaceOfPrefix("xsi");

            DataTable dt = QueryDataBase();

            foreach (DataRow row in dt.AsEnumerable())
            {
                XElement submission = new XElement(EN + "Submission");
                submission.Add(new object[] {
                new XAttribute(EN + "submissionFileCreatedDate", row.Field<DateTime>("submissionFileCreatedDate")),
                new XAttribute(EN + "submissionFileName", row.Field<string>("submissionFileName")),
                new XAttribute(EN + "submissionID", row.Field<int>("submissionID"))
                });

                eDWR.Add(submission);


                XElement LabAccreditation = new XElement(EN + "LabIdentification", new object[] {
                    new XElement(EN + "LabAccreditationIdentifier", row.Field<string>("LabAccreditationIdentifier")),
                    new XElement(EN + "LabAccreditationAuthorityName", row.Field<string>("LabAccreditationAuthorityName"))
                });

                XElement labReport = new XElement(EN + "LabReport");
                XElement labIdentification = new XElement(EN + "LabIdentification");
                submission.Add(labReport);
                labReport.Add(labIdentification);
                labIdentification.Add(LabAccreditation);

                XElement sampleIdentification = new XElement(EN + "SampleIdentification", new object[] {
                    new XElement(EN + "LabSampleIdentifier", row.Field<int>("LabSampleIdentifier")),
                    new XElement(EN + "PWSIdentifier", row.Field<string>("PWSIdentifier")),
                    new XElement(EN + "PWSFacilityIdentifier", row.Field<string>("PWSFacilityIdentifier")),
                    new XElement(EN + "SampleRuleCode", row.Field<string>("SampleRuleCode")),
                    new XElement(EN + "SampleMonitoringTypeCode", row.Field<string>("SampleMonitoringTypeCode"))
                 });

                XElement sample = new XElement(EN + "Sample");
                labReport.Add(sample);
                XElement RecordID = new XElement(SDWIS + "RecordID", row.Field<int>("RecordID"));
                sample.Add(RecordID);
                sample.Add(sampleIdentification);


            }

            doc.Save(FILENAME);

        }
        public DataTable QueryDataBase()
        {
            DataTable dt = new DataTable();

            //Here is an example of getting a datatable from a database
            string SQL = "Enter Your SQL Here";
            string connStr = "Enter your database connection string here";

            //uncomment instructions below
            //SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
            //adapter.Fill(dt);


            //I will build a dummy datatable for your test case
            dt.Columns.Add("submissionFileCreatedDate", typeof(DateTime));
            dt.Columns.Add("submissionFileName", typeof(string));
            dt.Columns.Add("submissionID", typeof(int));
            dt.Columns.Add("LabAccreditationIdentifier", typeof(string));
            dt.Columns.Add("LabAccreditationAuthorityName", typeof(string));
            dt.Columns.Add("RecordID", typeof(int));
            dt.Columns.Add("LabSampleIdentifier", typeof(int));
            dt.Columns.Add("PWSIdentifier", typeof(string));
            dt.Columns.Add("PWSFacilityIdentifier", typeof(string));
            dt.Columns.Add("SampleRuleCode", typeof(string));
            dt.Columns.Add("SampleMonitoringTypeCode", typeof(string));


            dt.Rows.Add(new object[] {
                DateTime.Parse("2012-07-21"),
                "B_14271BJB.csv",
                1,
                "OR100024",
                "STATE",
                155628,
                123321,
                "OR4100237",
                "DIST-A",
                "TC",
                "RP"
            });


            return dt;
        }

    }
}
​

【讨论】:

  • 所以我会接受这个作为答案,但我不知道如何创建 XML 文件并将其保存在某个位置。我也不知道 (string[] args) 做了什么。我还有其他嵌套节点或以下提交的任何内容。有没有办法离线进行对话?这是我的 xml 示例的结尾,其中包括除一个之外的嵌套节点。
  • 还有。 . .如何查询数据库中的表以获取行,其中将有多个行(所有值都在每一行中),其中所有 Sample 元素堆叠在一起,然后所有 AnalyticalResults 堆叠在一起。
  • 我可以通过单击按钮让代码在静态空白中运行。要尝试将这个提交提交,我将如何打印或保存从您提供的代码生成的 XML?
  • 我更新了我的代码以显示从数据库获取数据的示例。对数据库的查询可能非常复杂,可能需要一个 JOIN 语句,并且可能最终出现在多个数据表中。我的代码非常简单,但应该可以帮助您入门。
  • 是的!非常感谢!一旦我了解了树是如何工作的,我整个下午都在努力获取您提供给我的代码中的其他 XML 元素,单击按钮来构建文件并保存它,它看起来就像我们使用的一样。不用担心 JOINS。事实上,这个项目只使用一张表中的所有信息。您的数据查询应该可以正常工作。我将不得不循环两次,一次用于样本实体,一次用于结果实体。该应用程序希望首先获取所有样品信息(水特征),然后是分析结果。周末愉快!我打算。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2020-11-18
相关资源
最近更新 更多