元素“Root”的命名空间必须来自架构命名空间“http://www.w3.org/2001/XMLSchema”?

Tim*_*fey 2 xml validation xsd saxparseexception

我有一个 xml 文档:

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Child name="MyType" compareMode="EQ"></Child>
</Root>
Run Code Online (Sandbox Code Playgroud)

我想在以下 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>
Run Code Online (Sandbox Code Playgroud)

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

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'.
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么Root必须在架构的命名空间中?那可能是我没有正确验证xml文档吗?

公共同步布尔值 isValid(String xmlFragment, File xmlSchema) 抛出 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;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*Kay 5

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