2010-05-10 29 views
2

我正在使用XML文檔,其中標籤必須具有一組屬性或另一組屬性。例如,它需要看起來像<tag foo="hello" bar="kitty" /><tag spam="goodbye" eggs="world" />,例如如何要求元素具有一組屬性或XSD架構中的另一個屬性?

<root> 
    <tag foo="hello" bar="kitty" /> 
    <tag spam="goodbye" eggs="world" /> 
</root> 

所以我有,我用xs:choice元兩種不同的屬性組之間進行選擇的XSD架構:

<xsi:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified"> 
    <xs:element name="root"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element maxOccurs="unbounded" name="tag"> 
        <xs:choice> 
         <xs:complexType> 
          <xs:attribute name="foo" type="xs:string" use="required" /> 
          <xs:attribute name="bar" type="xs:string" use="required" /> 
         </xs:complexType> 
         <xs:complexType> 
          <xs:attribute name="spam" type="xs:string" use="required" /> 
          <xs:attribute name="eggs" type="xs:string" use="required" /> 
         </xs:complexType> 
        </xs:choice> 
       </xs:element> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
</xsi:schema> 

但是,使用lxml當試圖加載這個模式,我得到以下錯誤:

>>> from lxml import etree 
>>> etree.XMLSchema(etree.parse("schema_choice.xsd")) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "xmlschema.pxi", line 85, in lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:118685) 
lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element': The content is not valid. Expected is (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))., line 7 

由於錯誤是我xs:choice元素的位置,我試着將它放在不同的地方,但無論我嘗試什麼,似乎都無法使用它來定義具有一組屬性(foobar)或另一個(spameggs)的標記。

這甚至可能嗎?如果是這樣,那麼正確的語法是什麼?

回答

4

不幸的是不可能在XML模式中使用具有屬性的選項。您需要在更高級別上實施此驗證。

+1

確實。我強烈建議使用RELAX NG進行任何類型的XML驗證,除非您需要它來執行XML Schema(XSLT,XQuery,WS- *等)。實際上,lxml可以在Python中處理RELAX NG - 請參閱http://stackoverflow.com/questions/1254919/how-do-i-validate-xml-document-via-relax-ng-schema-in-python – 2010-05-10 22:49:46

+0

你能把我鏈接到一些證明這一點的文檔? – 2010-05-10 22:51:57

+0

@Pavel:謝謝你的提示,我一定會在將來寫自己的模式的時候考慮一​​下。不幸的是,現在我只是在調試另一家公司的某人寫的無效模式,所以我被困在XSD中。 – 2010-05-10 22:53:38

相關問題