④XMLスキーマで選択値の定義

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


XMLスキーマで、選択値をチェックしてみます。
簡単なサンプルを作ってみます。


■SelectValue.xml

<?xml version="1.0"  encoding="UTF-8"?>
<greeting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="SelectValue.xsd" attribute="Hello World!!">Hello World!!</greeting>


■SelectValue.xsd

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

  <xsd:complexType name="greetingType">
    <xsd:simpleContent>
      <xsd:extension base="greetingString">
        <xsd:attribute name="attribute" type="greetingString" use="required" />
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>

  <xsd:simpleType name="greetingString">
    <xsd:restriction base="xsd:string">
      <xsd:enumeration value="Hello World!!" />
      <xsd:enumeration value="HELLO WORLD!!" />
    </xsd:restriction>
  </xsd:simpleType>

</xsd:schema>


「greetingString」型を選択値にしました。
選択値は、「」で定義します。
」で定義された値のみがチェックOKになります。

<xsd:enumeration value="Hello World!!" />
      <xsd:enumeration value="HELLO WORLD!!" />


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


エラーは出ませんね。


SelectValue.xmlタグ値を「HELLO WORLD!!」、attribute属性値を「Hello World!!123」に変更して、検証してみます。
■SelectValue.xml

<?xml version="1.0"  encoding="UTF-8"?>
<greeting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="SelectValue.xsd" attribute="Hello World!!123">HELLO WORLD!!</greeting>


「SelectValue.xsd」では、タグ値は選択値なのでOKですが、attribute属性値は選択値に含まれないので、検証エラーになります。