如何使用条件类型分配使类型依赖于属性值 [英] How to make type depend on attribute value using Conditional Type Assignment

查看:29
本文介绍了如何使用条件类型分配使类型依赖于属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 XML 文件

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>

我想做一个XSD,这样如果属性type"的值为1,name和surname元素必须存在,当它是2时,name和id必须存在.我试图在 XSD 模式生成器中生成 XSD,但它生成了 surname 和 id 元素minOccurs=0.我怎样才能让它工作?

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?

推荐答案

您可以使用 XSD 1.1 的 条件类型赋值:

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>

这篇关于如何使用条件类型分配使类型依赖于属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆