2

我有一个 xml 文档:

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Child name="MyType" compareMode="EQ"></Child>
</Root>

我想在以下 xsd 的帮助下验证这个 xml:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Child">
          <xs:complexType>
            <xs:attribute name="name" type="xs:string" use="required" />
            <xs:attribute name="compareMode" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

当我尝试验证它时,我收到以下错误:

Exception in thread "main" org.xml.sax.SAXException: Validation failed against correct.xml. ErrorMessage:s4s-elt-schema-ns: The namespace of element 'Root' must be from the schema namespace, 'http://www.w3.org/2001/XMLSchema'.

我的问题是为什么Root必须在模式的名称空间中?会不会是我验证 xml 文档不正确?

public synchronized boolean isValid(String xmlFragment, File xmlSchema) throws SAXException, IOException{

// 1. 查找 W3C XML Schema 语言的工厂

SchemaFactory factory = 
    SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

// 2. Compile the schema. 

Schema schema = factory.newSchema(xmlSchema);

// 3. Get a validator from the schema.
Validator validator = schema.newValidator();

// 4. Parse the document you want to check.
Source source = new StreamSource(new ByteArrayInputStream(xmlFragment.getBytes()));

// 5. Check the document    
    validator.validate(source);        
    return true;
}
4

2 回答 2

5

难道 xmlSchema 保存的不是您向我们展示的架构,而是 W3C 发布的“架构文档的架构”?错误消息片段“ErrorMessage:s4s-elt-schema-ns:”似乎暗示了这一点。

于 2011-02-07T15:27:01.573 回答
1

该文档在定义的架构下有效,因此它必须与代码有关。

对所需命名空间(如错误消息中指定)的唯一显式引用是在SchemaFactory.newInstance调用中。如果你在那里传递一个空的 ("") 命名空间会发生什么?

此外,在模式中的 XML 文档中显式设置预期的名称空间也是一种很好的方式。有几种方法可以做到这一点。由于您选择为 XMLSchema 命名空间添加前缀,因此我建议您添加xmlns="" targetNamespace=""到您的<xs:schema标签中。

于 2011-02-07T14:53:04.253 回答