XSD: How to validate the XML file according to value of some tag?

后端 未结 4 595
醉梦人生
醉梦人生 2020-12-19 11:13

I was trying to validate this XML file ... where if

  1. is \"Y\" then must appear

  2. if

相关标签:
4条回答
  • 2020-12-19 11:26

    It's a known fact that this is a handycap of XML schema. But I would appreciate your approach of trying the <choice> tag. It could be successful if your conditions were something like this:

    1. If <tag1> is required and appears first then <tag2> isn't required (and appears as second tag)
    2. If <tag2> is required and appears first then <tag1> isn't required (and appears as second)

    The code is:

    <xs:element name="parent">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="a" maxOccurs="unbounded">
            <xs:complexType>
              <xs:choice>
                <xs:sequence>
                  <xs:element name="tag1" type="xs:boolean" />
                  <xs:element name="tag2" type="xs:string" minOccurs="0" />
                </xs:sequence>
                <xs:sequence>
                  <xs:element name="tag2" type="xs:string" />
                  <xs:element name="tag1" type="xs:boolean" minOccurs="0" />
                </xs:sequence>
              </xs:choice>
            </xs:complexType>
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
    
    0 讨论(0)
  • 2020-12-19 11:33

    You cannot validate things like that with XSD.

    XML schema is not designed and not intended to check "intra-tag" relationships, e.g. "tag2 must be present if tag1's value is 'Y'" - just cannot be done, sorry.

    If you need to check these kind of conditions, you'll have to look at Schematron to do that.

    0 讨论(0)
  • 2020-12-19 11:37

    Its not possible with XSD .. But by the way you can work around something like Infant-programmer if the requirement is bit comfortable as shown in her example ..

    0 讨论(0)
  • 2020-12-19 11:41

    Unfortunately this problem cannot be fixed using XSD. The reason is that XSD can only be used to define the structure (syntax) of XML-Files. What you would like to do is to couple the syntax to some semantic properties (some TAG must have a certain content to decide on the syntax of some TAGS nearby).

    0 讨论(0)
提交回复
热议问题