2011-03-18 103 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等) - 這總是四位數字,還是純粹巧合,你給我們展示的所有值都是四位數字?

有很多工具在從單個實例生成模式方面做得相當不錯,但他們必須猜測上述問題的答案。