2011-12-02 36 views
1

如果我與< anyattribute/>元素兩個元素在我的模式是這樣的:Xml架構與AnyAttribute,添加屬性特定元素

<xs:element name="NodeType1"> 
    <xs:complexType> 
    <xs:anyAttribute /> 
    </xs:complexType> 
</xs:element> 

<xs:element name="NodeType2"> 
    <xs:complexType> 
    <xs:anyAttribute /> 
    </xs:complexType> 
</xs:element> 

是否有可能只是延長另一個這些元素中的一個架構?假設我想僅爲NodeType2添加屬性。

回答

7

元素不可擴展;一般來說,如果您希望將其用作其他任何位置的擴展基礎,則必須創建一個名爲(全局,在架構元素下)的類型,即在相同或另一個XML架構中。

你的問題非常有趣,因爲它真的讓人懷疑,擴展東西的目的是什麼,無論如何,根據定義可以匹配任何東西。爲此,擴展的效果是相反的;它會爲擴展名中指定的屬性創建一個約束。

所以,第一個XSD:

<?xml version="1.0" encoding="utf-8" ?> 
<!--W3C Schema generated by QTAssistant/W3C Schema Refactoring Module (http://www.paschidev.com)--> 
<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" 
    elementFormDefault="qualified" 
    xmlns="http://tempuri.org/XMLSchema.xsd" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

    <xsd:element name="root" type="BaseType"/> 

    <xsd:complexType name="BaseType"> 
     <xsd:anyAttribute processContents="lax" /> 
    </xsd:complexType> 

    <xsd:complexType name="Extending"> 
     <xsd:complexContent> 
      <xsd:extension base="BaseType"> 
       <xsd:attribute name="new1" type="xsd:int"/> 
      </xsd:extension> 
     </xsd:complexContent> 
    </xsd:complexType> 
</xsd:schema> 

有了這個模式,下面的示例XML是完全有效的:現在

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) --> 
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" new1="S" new2="2" xmlns="http://tempuri.org/XMLSchema.xsd"/> 

,如果我改變了

<xsd:element name="root" type="BaseType"/> 

<xsd:element name="root" type="Extending"/> 

同一樣本XML如果不再有效:

Error occurred while loading [], line 3 position 61 
The 'new1' attribute is invalid - The value 'S' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:int' - The string 'S' is not a valid Int32 value. 

的S改變爲一個數值,它將使XML有效。

對於「擴展」,這不是一件有趣的事嗎?...