问题
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