XSD定义了我要映射到一个类

时间:2016-05-27 11:05:42

标签: c# .net xml xslt xsd

我们消费的Feed包含以下元素:

<animals>
<cow>
 <name>Daisy</name>
 <weight>250</weight>
 <age>4</age>
</cow>
<pig>
 <name>45tyyy</name>
 <weight>80</weight>
 <age>2</age>
</pig>
<sheep>
 <name>Lamby</name>
 <weight>50</weight>
 <age>7</age>
</sheep>
</animals>

XSD可能如下所示:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="animals">
    <xs:complexType>
      <xs:choice maxOccurs="unbounded" minOccurs="0">
        <xs:element name="cow">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:short" name="weight"/>
              <xs:element type="xs:byte" name="age"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="pig">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:byte" name="weight"/>
              <xs:element type="xs:byte" name="age"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="sheep">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:short" name="weight"/>
              <xs:element type="xs:byte" name="age"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

然而,在我们的C#代码(和数据库)中,它们只是不同类型的动物,所以如果饲料形式如此,我们就会容易得多:

<animal type="cow">
 <name>Daisy</name>
 <weight>250</weight>
 <age>4</age>
</animal>

或:

<animal>
 <type>Cow</type>
 <name>Daisy</name>
 <weight>250</weight>
 <age>4</age>
</animal>

我们希望使用XSD.exe或XSD2Code等自动工具生成映射到XML的类,因此我们只需要一个Animal类来处理。

我们无法更改Feed,但我们可以修改我们用来生成代码的XSD(如果有帮助的话) - 例如定义扩展的基类<animal>类型,希望C#类可以包括基类Animal?

另一种选择是我们可以将XML转换为我们希望的格式,而不是稍微修改过的XSD,大概是使用XSLT吗?

我没有用XSD或XSLT做过很多,特别是在C#中没有做过那么可以我如何使用输入XML并使用代码生成工具将其映射到单个Animal类?

1 个答案:

答案 0 :(得分:1)

  

另一个选择是我们可以将XML转换为我们希望的格式   针对略有修改的XSD,可能是使用XSLT?

这在XSLT中非常简单:

<div class="qic-form-group showError">
	<input onKeyDown="if(this.value.length==9 && event.keyCode != 8)return false;" class="clearTxtFld number" placeholder="Vehicle Value"  name="vehicleValue">
</div>

这不需要XSD。