XSD 空元素

XSD「空元素」(Empty Element)最全实用总结

—— 只有属性、没有任何内容(文本或子元素)的元素

典型场景:<br/><img src="..." /><hr id="separator"/>、业务中常见的各种“标记”或“配置点”。

1. 空元素的三种标准写法(99% 项目只用这三种)

写法XSD 代码(推荐度)对应合法 XML 示例典型业务场景
1推荐 匿名空 complexType(最常见)<xs:element name="br">
<xs:complexType/>
</xs:element>
<br/><hr/>(XHTML)
2推荐 命名空 complexType(可复用)先定义:
<xs:complexType name="EmptyType"/>
再引用:
<xs:element name="break" type="EmptyType"/>
可复用的空标记、配置开关
3推荐 最清晰的带属性空元素(企业标配)“`xml

2. 企业级真实空元素模板(直接复制)

<!-- 1. 分隔线(最纯粹的空元素)-->
<xs:element name="hr">
  <xs:complexType/>
</xs:element>

<!-- 2. 图片(最经典的空元素)-->
<xs:element name="img">
  <xs:complexType>
    <xs:attribute name="src"   type="xs:anyURI"      use="required"/>
    <xs:attribute name="alt"   type="xs:string"      use="optional"/>
    <xs:attribute name="width" type="xs:positiveInteger" minOccurs="0"/>
    <xs:attribute name="height"type="xs:positiveInteger" minOccurs="0"/>
  </xs:complexType>
</xs:element>

<!-- 3. 业务中常见的“配置开关”空元素 -->
<xs:element name="feature">
  <xs:complexType>
    <xs:attribute name="name"  type="xs:string" use="required"/>
    <xs:attribute name="enabled" type="xs:boolean" default="true"/>
  </xs:complexType>
</xs:element>
<!-- 使用例 -->
<feature name="darkMode" enabled="true"/>
<feature name="betaFunction"/>

<!-- 4. 通用可复用空类型(大厂最爱)-->
<xs:complexType name="EmptyWithId">
  <xs:attribute name="id" type="xs:ID" use="required"/>
</xs:complexType>

<xs:element name="separator" type="EmptyWithId"/>
<xs:element name="placeholder" type="EmptyWithId"/>
<!-- 使用例 -->
<separator id="section-1"/>

3. 一句话写空元素的终极公式(永远不会错)

<xs:element name="你的空元素名">
  <xs:complexType>
    <!-- 什么都不写 = 纯空 -->
    <!-- 只写属性 -->
    <xs:attribute name="xxx" type="..." use="required"/>
    <xs:attribute name="yyy" type="..." default="..."/>
  </xs:complexType>
</xs:element>

只要 <xs:complexType>没有 <xs:sequence><xs:choice><xs:all>、mixed=”true”,它就是空元素!

4. 常见错误 vs 正确写法

错误写法正确写法后果
<xs:complexType></xs:complexType> 外面没包 element必须包在 <xs:element>无法在 XML 中使用
写了 <xs:sequence/>删掉或留空 <xs:complexType/>变成可以有子元素的非空元素
写了 <xs:simpleContent>空元素不能有 simpleContent语法错误
想让元素可选但又写空元素直接在引用处加 minOccurs="0"空元素本身不需要

记住:空就真的空!
只要看到 <xs:complexType> 里面什么都不写(或只有 attribute),它就是完美的空元素。

需要我立刻给你生成任意业务的空元素(比如 <cache/><lock/><timeout/><placeholder/>),告诉我名字和要带的属性就行,5 秒出成品!

文章已创建 2783

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部