首页 > 解决方案 > 我想
在 XML 中的 CDATA 中发送标签。哪个没有在 XSD 中得到验证

问题描述

我想
在 XML 中的 CDATA 中发送标签。哪个没有在 XSD 中得到验证。在 XSD 中使用序列。我的 XML 是这样的。

<hotelnotes>
    <hotelnote><![CDATA[This is <br> Hotel Note <br> End of hotel note]]></hotelnote>
</hotelnotes>

XSD

  <xs:element name="hotelnotes">
      <xs:complexType>
        <xs:sequence>
          <xs:element type="xs:string" name="hotelnote" minOccurs="0"/>
        </xs:sequence>
      </xs:complexType>
  </xs:element>

标签: javastringxsdxsd-validationxsd-1.1

解决方案


如果您想确保<br>标签位于酒店注释中的文本内,您可以使用基于字符串类型的简单类型,并带有模式限制。

以下是此类限制的示例:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="hotelnotes">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="hotelnote" minOccurs="0">
                    <xs:simpleType>
                        <xs:restriction base="xs:string">
                            <xs:pattern value=".+&lt;br\s*&gt;.+" />
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

该文件将根据上面的 XSD 代码进行验证:

<?xml version='1.0' encoding='utf-8'?>
<hotelnotes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="../xsd/hotel_example.xsd">
    <hotelnote><![CDATA[This is <br> Hotel Note End of hotel note]]></hotelnote>
</hotelnotes>

而这个不会,因为它不包含<br>标签:

<?xml version='1.0' encoding='utf-8'?>
<hotelnotes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="../xsd/hotel_example.xsd">
    <hotelnote><![CDATA[This is Hotel Note End of hotel note]]></hotelnote>
</hotelnotes>

更新:

如果您需要在 CDATA 中接受更通用的字符串,您可以使用此 XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="hotelnotes">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="hotelnote" minOccurs="0" >
                    <xs:simpleType>
                        <xs:restriction base="xs:string">
                            <xs:pattern value=".+" /><!-- Enter here whichever regular expression which imposes a limitation on the string in CDATA -->
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

上面的版本只要求 CDATA 块中至少有一个字符。


推荐阅读