XSD如何使用模式验证<any>?</any>

时间:2015-01-28 12:43:58

标签: xml validation xsd any

如果我使用<xs:any processContents="strict"/>,那么我该如何为它提供架构?

message.xsd:

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

<xs:element name="message">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="sender" type="xs:string"/>
      <xs:element name="content">
        <xs:complexType>
          <xs:sequence>
            <xs:any processContents="strict"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

content.xsd:

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

<xs:element name="text" type="xs:string" />

</xs:schema>

message.xml:

<?xml version="1.0"?>
<message xmlns="messageNS"
         xmlns:c="contentNS"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="messageNS message.xsd
                             contentNS content.xsd">     
    <sender>gfdgf</sender>
    <content>
        <c:text>asdsad</c:text>
    </content>
</message>

如果我尝试验证message.xml,则会收到以下错误:

cvc-complex-type.2.4.c:匹配的通配符是strict,但是找不到元素'c:text'的声明。

我正在使用标准的Java验证器:javax.xml.validation.Validator;

1 个答案:

答案 0 :(得分:1)

创建一个Schema,它是所有可能的架构源的集合:

SchemaFactory f;
Source messageSource = // your message.xsd;
Source contentSource = // your content.xsd;
Schema schema = f.newSchema(messageSource, contentSurce);
Validator v = schema.newValidator();

然后像往常一样使用Validator