简体   繁体   中英

XML validation for empty decimal element with precision attribute

I have an issue validating an empty element against an XSD which contains the definition below. If the total_amt comes out to be empty, we want an empty element in the XML document, like

<total_amt/>

So I have created a custom datatype in XSD as shown below:

<xs:simpleType name="decimal-or-empty">
  <xs:union memberTypes="xs:decimal empty-string" />
</xs:simpleType>

<xs:simpleType name="empty-string">
  <xs:restriction base="xs:string">
    <xs:enumeration value="" />
  </xs:restriction>
</xs:simpleType>

And the XSD definition of the element is shown below.

<xs:element name = "total_amt" 
            nillable="false" 
            minOccurs="0" 
            type="decimal-or-empty">
     <xs:complexType>
       <xs:SimpleContent>
         <xs:extension base="xs:decimal">
            <xs:attribute name="precision" 
                          type="xs:integer"/>
        </xs:extension>
      </xs:SimpleContent>
   </xs:complexType>
</xs:element>

If I remove the precision attribute in the above XSD, then it validates the custom data type and it works well with empty value

<xs:element name = "total_amt" 
            nillable="false" 
            minOccurs="0" 
            type="decimal-or-empty">
</xs:element>

but when I define the precision attribute, the result is always that the XML instance is invalid.

So, Can anyone please help me in writing XSD where I can put the precision attribute and still validate the XML when the value of the total_amt is empty?

Your complex type adds a precision attribute to xs:decimal:

<xs:extension base="xs:decimal">
  <xs:attribute name="precision" 
                type="xs:integer"/>
</xs:extension>

Why not add it to decimal-or-empty instead?

<xs:extension base="decimal-or-empty">
  <xs:attribute name="precision" 
                type="xs:integer"/>
</xs:extension>

That is, I don't think it's the presence of the attribute declaration that's causing your problem: it's that your union type is no longer used.

You might consider using xsi:nil for this instead, though it requires that your empty element be

<total_amt xsi:nil="true"/>

instead of just

<total_amt/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM