【问题标题】:Define an XML element that must be empty and has no attributes定义一个必须为空且没有属性的 XML 元素
【发布时间】:2013-12-23 21:57:19
【问题描述】:

我需要定义一个没有子元素或任何内容,并且没有属性的 XML 元素。

这就是我正在做的:

<xs:element name="myEmptyElement" type="_Empty"/>
<xs:complexType name="_Empty">
</xs:complexType>

这似乎工作正常,但我想知道是否有办法做到这一点而不必声明复杂类型。另外,如果我有什么问题,请告诉我。

预计有人可能会好奇我为什么需要这样一个元素:它用于不需要任何参数值的 SOAP 操作。

【问题讨论】:

    标签: xml xsd


    【解决方案1】:

    (1) 你可以避免定义一个命名的xs:complexType

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="myEmptyElement">
        <xs:complexType/>
      </xs:element>
    </xs:schema>
    

    (2) 您可以使用xs:simpleType 代替xs:complexType

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="myEmptyElement">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:maxLength value="0"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:element>
    </xs:schema>
    

    (3) 你可以使用fixed="" [credit: @Nemo]:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="myEmptyElement" type="xs:string" fixed=""/>
    </xs:schema>
    

    (4) 但请注意,如果您避免提及内容模型:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="myEmptyElement"/>
    </xs:schema>
    

    您将允许 myEmptyElement 中的任何属性和任何内容。

    【讨论】:

    • 这是针对 SOAP Web 服务的,我使用soapUI 进行测试。当soapUI自动生成请求时,它会为#1生成&lt;web:getServerInfo/&gt;,但为#2和#3生成&lt;web:getServerInfo&gt;?&lt;/web:getServerInfo&gt;
    • 我想知道#2 之类的东西是否可以使用xs:simpleType,但具有讽刺意味的是,它比使用xs:complexType 更冗长。我也不喜欢它说内容是一个字符串,尽管是一个空字符串。
    • 我想像&lt;xs:element name="myEmptyElement" type="xs:empty"/&gt; 这样的东西要求太多了。因此,我将选择#1。由于我只有一个这样的元素,因此不值得定义命名类型。
    【解决方案2】:

    另一个例子可能是:

    <xs:complexType name="empty">
        <xs:sequence/>
    </xs:complexType>
    <xs:element name="myEmptyElement" type="empty>
    

    <xs:element name="myEmptyElement">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value=""/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    

    <xs:element name="myEmptyElement">
        <xs:complexType>
            <xs:complexContent>
                <xs:restriction base="xs:anyType"/>
            </xs:complexContent>
        </xs:complexType>
    </xs:element>
    

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 2012-01-23
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多