⑧XMLスキーマで階層構造の定義(定義した要素のどれかが出現すればいい場合)

XMLスキーマの書き方について、学んだ事を書いていきます。


XMLスキーマで階層構造を定義してみます。(定義した要素のどれかが出現すればいい場合)
簡単なサンプルを作ってみます。


■Choice.xml

<?xml version="1.0"  encoding="UTF-8"?>
<nameList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Choice.xsd">
  <id>1</id>
</nameList>


■Choice.xsd

<?xml version="1.0"  encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="nameList" type="nameListType" />

  <xsd:complexType name="nameListType">
    <xsd:choice>
      <xsd:element name="id" type="xsd:string"/>
      <xsd:element name="name" type="xsd:string"/>
    </xsd:choice>
  </xsd:complexType>

</xsd:schema>


「nameListType」を定義しました。
タグの子要素は、タグとタグです。
「xsd:choice」で定義しているので、タグ、タグのどちらかが出現すればOKです。

<xsd:complexType name="nameListType">
    <xsd:choice>
      <xsd:element name="id" type="xsd:string"/>
      <xsd:element name="name" type="xsd:string"/>
    </xsd:choice>
  </xsd:complexType>


Eclipseで、XMLスキーマ検証してみます。
XMLファイルを開いて、右クリックメニューの「検証」で、XMLスキーマ検証します。


エラーは出ませんね。


Choice.xmlタグを削除して、タグに入れ替えて、検証してみます。
■Choice.xml

<?xml version="1.0"  encoding="UTF-8"?>
<nameList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Choice.xsd">
  <name>hogehoge</name>
</nameList>


「Choice.xsd」では、タグ、タグのどちらかが出現すればいいので、検証OKになります。
タグ、タグの両方を記載すると、検証エラーになります。