2010-05-10 62 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

相关问题