2010-10-10 96 views
1

我是XML新手,目前我正在使用XSD。我应该验证基于信用卡的xml文档。我已经完成了大部分任务,但我坚持声明一个必须是正浮点数的元素,同时也允许该元素具有必需的属性,该属性必须具有与其关联的3字母货币类型。XSD限制xsd类型,同时允许属性

下面是XML元素的一个例子我要验证:

<total curId="USD">4003.46</total> 

这是我有:

<xsd:element name="total" type="validAmount"/> 

    <xsd:complexType name="validAmount"> 
     <xsd:simpleContent> 
      <xsd:extension base="xsd:decimal"> 
       <xsd:attribute name= "curId" type = "currencyAttribute" use="required"/> 
      </xsd:extension> 
     </xsd:simpleContent> 
    </xsd:complexType> 

对于curId属性:

<xsd:simpleType name="currencyAttribute"> 
    <xsd:restriction base="xsd:string"> 
     <xsd:pattern value="[A-Z]{3}"/> 
    </xsd:restriction> 
</xsd:simpleType> 

的我遇到的问题是试图将扩展名更改为限制,允许小数为正数(也许是将其类型更改为字符串并使用模式面将其限制为正数)。但是,如果我这样做,我用来验证xml文档的脚本会抛出错误。我知道我可能错过了一些显而易见的东西,但正如我所说的,我对此很陌生,因此任何帮助都将不胜感激。

回答

0

XSD不允许你在一个“镜头”中达到你想要的效果;您需要首先定义受限制的简单类型(在restrictedDecimal类型中),然后使用属性扩展该属性(这里的关键是使用simpleContent)。

<?xml version="1.0" encoding="utf-8" ?> 
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) --> 
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element name="total" type="validAmount"/> 

    <xsd:simpleType name="restrictedDecimal"> 
     <xsd:restriction base="xsd:decimal"> 
      <xsd:minInclusive value="0"/> 
     </xsd:restriction> 
    </xsd:simpleType> 

    <xsd:complexType name="validAmount"> 
     <xsd:simpleContent> 
      <xsd:extension base="restrictedDecimal"> 
       <xsd:attribute name= "curId" type = "currencyAttribute" use="required"/> 
      </xsd:extension> 
     </xsd:simpleContent> 
    </xsd:complexType> 

    <xsd:simpleType name="currencyAttribute"> 
     <xsd:restriction base="xsd:string"> 
      <xsd:pattern value="[A-Z]{3}"/> 
     </xsd:restriction> 
    </xsd:simpleType> 
</xsd:schema>