从SQL现有XSD文件生成XML(复杂)

时间:2017-02-15 07:58:01

标签: c# sql-server xml xsd

我有一个XSD文件。我从SQL获取数据并将数据填充到数据集中。 注意:我从SQL获得了1000条记录。

我想做到这一点;生成现有xsd格式的XML文件。

这是我的XSD。:

 <xs:element name = 'automation'>
  <xs:complexType>
     <xs:sequence>
          <xs:element name = 'auto' type = 'AutoType' minOccurs = '1' maxOccurs = 'unbounded' />
     </xs:sequence>
  </xs:complexType>

<xs:complexType name = "AutoType">
  <xs:sequence>
     <xs:element name = "autoKodu" type = "xs:string" minOccurs = '1' maxOccurs = '1' /> <!-- v -->
     <xs:element name = "autoAdres" type = "xs:string" minOccurs = '1' maxOccurs = '1' /> <!-- v -->
     <xs:element name = 'bill' type = 'BillType' minOccurs = '1' maxOccurs = 'unbounded' />
  </xs:sequence>

 <xs:complexType name = "BillType">
  <xs:sequence>
     <xs:element name = "dateOne" type = "xs:date" minOccurs = '1' maxOccurs = '1' /> 
     <xs:element name = "dateTwo" type = "xs:time" minOccurs = '1' maxOccurs = '1' /> 
     <xs:element name = 'point' type = 'PointType' minOccurs = '1' maxOccurs = 'unbounded' />

  </xs:sequence>

<xs:complexType name = "PointType">
  <xs:sequence>
      <xs:element name = "plate"  minOccurs = '1' maxOccurs = '1' > <!-- v -->
     <xs:simpleType>
        <xs:restriction base="xs:string">
          <xs:pattern value="([a-zA-Z0-9])*"/>
        </xs:restriction>
      </xs:simpleType>
      </xs:element>
     <xs:element name = "aa" type = "xs:string" minOccurs = '1' maxOccurs = '1' /> 
     <xs:element name = "bb" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' /> 
     <xs:element name = "cc" type = "xs:string" minOccurs = '1' maxOccurs = '1' /> 
     <xs:element name = "dd" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
     <xs:element name = "ee" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' /> 
     <xs:element name = "ff" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
     <xs:element name = "gg" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
     <xs:element name = "hh" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
  </xs:sequence>

我使用xsd.exe创建了xsd类 我把它添加到解决方案中。

var data = new myClassOrSmthng? { ??? I do not know how to get datas from dataset here. }

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

1 个答案:

答案 0 :(得分:0)

从Visual Studio命令提示符中,运行以下命令以创建类文件:

xsd.exe /c automation.xsd (the XSD file you have)

将该类文件添加到您的项目中(例如Automation.cs)。

然后,您可以使用该类序列化XML:

StringReader objStringReader = new StringReader(strXML);
XmlSerializer objXmlSerializer = new XmlSerializer(typeof(Automation));
Automation automationInstance = (objXmlSerializer.Deserialize(StringReader) as Automation);