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

标签 xml validation xsd saxparseexception

我有一个 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. Lookup a factory for the W3C XML Schema language

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;
}

最佳答案

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

关于xml - 元素 'Root' 的命名空间必须来自架构命名空间 'http://www.w3.org/2001/XMLSchema' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4922452/

相关文章:

xml - 根据子节点过滤 XML

c# - 在 C# 中验证输入字段

xml - 指定 XML 架构数据类型为小数或空白

java - 从 sax validator 获取更多信息

javascript - 无法在javascript中加载xml文件

javascript - 使用 Javascript/E4X 计算 XML 片段中的节点数

java - Ant 在内存不足时调用 taskkill

javascript - 如果表单无效,是否会调用提交?

forms - CakePHP 3 如何在不更改密码的情况下编辑用户(散列)

xslt - 如何使用 XSLT 从 XSD 生成简单文档