【问题标题】:SAXException when parsing XML file with XSD schema使用 XSD 模式解析 XML 文件时出现 SAXException
【发布时间】:2010-10-06 16:29:53
【问题描述】:

我有以下 XSD 文件:

<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'
           targetNamespace='http://www.wvf.com/schemas'
           xmlns='http://www.wvf.com/schemas'
           xmlns:acmewvf='http://www.wvf.com/schemas'>

 <xs:element name='loft'>
 </xs:element>
</xs:schema>

以及以下 XML 文件:

<?xml version="1.0"?>

<acmewvf:loft xmlns:acmewvf="http://www.wvf.com/schemas"
               xmlns="http://www.wvf.com/schemas">
</acmewvf:loft>

当我执行以下 Java 代码时:

public void parse(InputStream constraints) {
    final SchemaFactory schemaFactory = new XMLSchemaFactory();
    final URL resource = 
        ClassLoader.getSystemClassLoader().getResource(SCHEMA_PATH);
    final DocumentBuilderFactory factory = 
        DocumentBuilderFactory.newInstance();
    Document doc = null;
    factory.setSchema(schemaFactory.newSchema(resource));
    final DocumentBuilder builder = factory.newDocumentBuilder();
    doc = builder.parse(constraints);

我得到以下 SAXException(在代码的最后一行):

cvc-elt.1:找不到声明 元素'acmewvf:loft'。

(请注意,SCHEMA_PATH 指向上面给出的内容的 XSD 文件,约束是上面给出的 XML 文件的输入流。)

这里出了什么问题?

【问题讨论】:

  • 尝试在 xml 中包含这个
  • 能否说得更具体一些?

标签: java xml xsd sax


【解决方案1】:

Using the Validating Parser。或许,您应该尝试添加以下内容以生成可识别命名空间的验证解析器:

  factory.setNamespaceAware(true);
  factory.setValidating(true);
try {
  factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
} 
catch (IllegalArgumentException x) {
  // Happens if the parser does not support JAXP 1.2
  ...
} 

别忘了定义:

static final String JAXP_SCHEMA_LANGUAGE =
    "http://java.sun.com/xml/jaxp/properties/schemaLanguage";

static final String W3C_XML_SCHEMA =
    "http://www.w3.org/2001/XMLSchema"; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2014-05-13
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多