Define an element with attribute and optional value

你说的曾经没有我的故事 提交于 2020-01-07 04:59:07

问题


How do I create an xsd that can validate either of the following two examples?

<element attribute="attribute-value" />

and

<element attribute="attribute-value">element-value</element>

回答1:


  <?xml version="1.0" encoding="utf-8"?>
  <xs:schema id="test"
      targetNamespace="http://tempuri.org/test.xsd"
      elementFormDefault="qualified"
      xmlns="http://tempuri.org/test.xsd"
      xmlns:mstns="http://tempuri.org/test.xsd"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
  >
    <xs:complexType name="element_type">
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="attribute" type="xs:string" />
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>

    <xs:element name="root">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="element" type="element_type">
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:schema>

This assumes that the attribute isn't required.




回答2:


You would use xsd:simpleContent for this. Here is an example.




回答3:


For completeness, I added some validation parameters as follows:

<xsd:element name="element">
  <xsd:complexType>
    <xsd:simpleContent>
        <xsd:extension base="OptionalString">
            <xsd:attribute name="row" type="xsd:positiveInteger"
                use="required" />
        </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>
</xsd:element>

<xsd:simpleType name="OptionalString">
<xsd:restriction base="xsd:string">
    <xsd:minLength value="0" />         
</xsd:restriction>
</xsd:simpleType>

Would this be different from the solution proposed above?



来源:https://stackoverflow.com/questions/8859702/define-an-element-with-attribute-and-optional-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!