XML Schema to restrict one field based on another

…衆ロ難τιáo~ 提交于 2019-12-07 07:10:23

问题


I have the following schema, which I use to ensure that a person's PhoneNumber and PhoneNumberType (Home, Work, etc.) is not longer than 10 characters. However, I want to improve this schema so that PhoneNumberType is not required if a PhoneNumber is not provided, but is required if the PhoneNumber is provided. Is there a way to do this in XML Schema 1.0?

I am aware this could be accomplished in XML Schema 1.1 using <xs:assert/>, but unfortunately I am stuck with XML Schema 1.0.

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xs:element name="PhoneNumber">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:minLength value="0"/>
        <xs:maxLength value="10"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
  <xs:element name="PhoneNumberType">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:minLength value="0"/>
        <xs:maxLength value="10"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xsd:schema>

回答1:


Sorry, XML Schema can't do that.

Some similar questions:

  • can the length of two xml lists be defined as being required to be equal?
  • Restrict Element Values Based on Attribute
  • How to use attribute value as a discriminator for XML polymorphic type selection?
  • How to Validate in XSD the xml node value against it’s neighbor xml node value



回答2:


It seems to me that this is a "has" relationship.

If you have a PhoneNumber element, then it should have a property that is of type PhoneNumberType. Rather than messing around with validating and restrictions, I would suggest that you turn PhoneNumber into a complex element and make PhoneNumberType a required property of it.




回答3:


May be too late, but you can put them in group like this

<xs:group name="group">
<xs:sequence>
    <xs:element ref="PhoneNumber"/>
    <xs:element ref="PhoneNymberType" />
</xs:sequence>

And make this group required or not



来源:https://stackoverflow.com/questions/2518384/xml-schema-to-restrict-one-field-based-on-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!