Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

xml - How to make type depend on attribute value using Conditional Type Assignment

I have an XML file like this

<listOfA>
  <a type="1">
    <name></name>
    <surname></surname>
  </a>
  <a type="2">
    <name></name>
    <id></id>
  </a>
</listOfA>

I'd like to make an XSD, so that if the value of the attribute "type" is 1, the name and surname elements must be present, and when it's 2, name and id must be there. I tried to generate the XSD in XSD schema generator, but it made the surname and id element minOccurs=0. How could I make it work?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using XSD 1.1's Conditional Type Assignment:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           elementFormDefault="qualified"
           vc:minVersion="1.1"> 
  <xs:element name="listOfA">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="a" maxOccurs="unbounded">
          <xs:alternative test="@type = 1" type="a1Type"/>        
          <xs:alternative test="@type = 2" type="a2Type"/>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="a1Type">
    <xs:sequence>
      <xs:element name="name"/>
      <xs:element name="surname"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="a2Type">
    <xs:sequence>
      <xs:element name="name"/>
      <xs:element name="id"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...