XML 架构:如何允许元素具有属性但没有文本?

XML Schema: How do I allow an element with attributes but no text?

我正在尝试创建一个 XSD 来验证 XML 文件,并且有几个元素需要有属性但没有文本。

例如这应该被认为是有效的:

<DEPRECATED value="blah"/>

这些无效:

<DEPRECATED>blah</DEPRECATED>
<DEPRECATED value="blah">bad text</DEPRECATED>

我尝试按照 here 中的描述声明一个复杂的空元素,但要么是我对示例的解释不正确,要么是示例本身是错误的(请参阅下面的错误):

<xs:element name="DEPRECATED" type="stringValue" minOccurs="0" maxOccurs="1"/>

<xs:complexType name="stringValue">
        <xs:complexContent>
            <xs:restriction base="xs:integer">
                <xs:attribute name="value" type="xs:string"/>
            </xs:restriction>
        </xs:complexContent>
</xs:complexType>

错误:类型 'stringValue' 的复杂类型定义表示错误。使用时,基类型必须是复杂类型。 'integer' 是一个简单类型。

我也试过这样定义 complexType:

<xs:complexType name="stringValue">
    <xs:attribute name="value" type="xs:string"/>
</xs:complexType>

但这会将上述无效示例视为有效。 [编辑:更正,以上 确实 有效。]

我也尝试过类似问题的答案 (Define an XML element that must be empty and has no attributes, Prevent Empty Elements in XML via XSD),但没有成功。

如何验证元素具有属性但没有文本?

这个XML会有效

<DEPRECATED value="blah"/>

和这个XML

<DEPRECATED>blah</DEPRECATED>

和这个XML

<DEPRECATED value="blah">bad text</DEPRECATED>

将无效使用此XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="DEPRECATED">
    <xs:complexType>
      <xs:attribute name="value"/>
    </xs:complexType>
  </xs:element>

</xs:schema>

我想你正在寻找这样的东西

<xs:schema elementFormDefault="qualified" version="1.0"
    targetNamespace="Whosebug" xmlns:tns="Whosebug"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="Test">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="DEPRECATED" type="tns:deprecatedType" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="deprecatedType">
        <xs:attribute name="number" />
    </xs:complexType>
</xs:schema>

此 XML 文件有效

<sf:Test xmlns:sf="Whosebug"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="Whosebug test.xsd">
    <sf:DEPRECATED number="123"/>
</sf:Test>

此 XML 文档无效

<sf:Test xmlns:sf="Whosebug"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="Whosebug test.xsd">
    <sf:DEPRECATED number="123">TEST</sf:DEPRECATED>
</sf:Test>

如果您想限制属性,您可能需要这样的东西:

<xs:complexType name="deprecatedType">
    <xs:attribute name="number">
        <xs:simpleType>
            <xs:restriction base="xs:string" />
        </xs:simpleType>
    </xs:attribute>
</xs:complexType>

试试这个:

  <xsd:simpleType name="EmptyType">
    <xsd:restriction base="xsd:string">
      <xsd:length value="0" />
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:complexType name="DeprecatedType">
    <xsd:simpleContent>
      <xsd:extension base="EmptyType">
        <xsd:attribute name="value" type="xsd:string" />
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>