2011-03-18 64 views
0

你如何为这个xml节编写XSD?如何为此XML编写XML模式?

<sales> 
    <orders> 
     <order type="online">1234</order> 
     <order type="online">2334</order> 
     <order type="retail">7834</order> 
     <order type="retail">5654</order> 
    </orders> 
</sales> 

回答

1

搜索c:\ program files for xsd.exe(Xml Schema Definition Tool)。然后用它作为xsd.exe c:\ your.xml。这是给你的XML-废品产量:

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema id="sales" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> 
    <xs:element name="sales" msdata:IsDataSet="true" msdata:Locale="en-US"> 
    <xs:complexType> 
     <xs:choice minOccurs="0" maxOccurs="unbounded"> 
     <xs:element name="orders"> 
      <xs:complexType> 
      <xs:sequence> 
       <xs:element name="order" nillable="true" minOccurs="0" maxOccurs="unbounded"> 
       <xs:complexType> 
        <xs:simpleContent msdata:ColumnName="order_Text" msdata:Ordinal="1"> 
        <xs:extension base="xs:unsignedShort"> 
         <xs:attribute name="type" type="xs:string" /> 
        </xs:extension> 
        </xs:simpleContent> 
       </xs:complexType> 
       </xs:element> 
      </xs:sequence> 
      </xs:complexType> 
     </xs:element> 
     </xs:choice> 
    </xs:complexType> 
    </xs:element> 
</xs:schema> 

...当然,也可能是,如果你理解的元素有点简化。

<xs:element name="sales"> 
    <xs:complexType>  
    <xs:sequence> 
     <xs:element name="orders"> 
     <xs:complexType> 
      <xs:sequence> 
      <xs:element name="order" maxOccurs="unbounded"> 
       <xs:complexType> 
       <xs:simpleContent> 
        <xs:extension base="xs:string"> 
        <xs:attribute name="type" type="xs:string"/>       
        </xs:extension> 
       </xs:simpleContent> 
       </xs:complexType> 
      </xs:element> 
      </xs:sequence> 
     </xs:complexType> 
     </xs:element> 
    </xs:sequence> 
    </xs:complexType> 
</xs:element> 
1

对于其中一种情况,您可以使用各种工具从XML中生成通用模式,但没有人会确切知道哪些约束很重要。例如,在您的示例中将“type”限制为“在线”还是“零售”非常重要?要做到这一点,你需要自己编写XML Schema。

尽管整个XML Schema都很复杂,但您可以通过阅读XML Schema Primer或其中一个教程获得基础知识。

1

您的XML文档是一个有效的实例,存在无数的模式。要编写一个模式,我们需要更多地了解这组有效的实例。例如,“在线”和“零售”是type属性的唯一有效值,还是存在其他有效值?内容如何(1234等) - 这总是四位数字,还是纯粹巧合,你给我们展示的所有值都是四位数字?

有很多工具在从单个实例生成模式方面做得相当不错,但他们必须猜测上述问题的答案。