1

我有一个 XSD 文件:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="someNameSpace"
    xmlns="someNameSpace"
    elementFormDefault="qualified">
...
</xs:schema>

在 Java 代码中:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
dbf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
dbf.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation", "someNameSpace file:///home/.../schema.xsd");

DocumentBuilder builder = dbf.newDocumentBuilder();
builder.setErrorHandler(new SomeHandlerImpl());
Document doc = builder.parse(input);

输入是一个文件,开头为:

<?xml version="1.0" encoding="UTF-8"?>
<projekt xmlns="someNameSpace">

如果我删除命名空间并改用http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation属性http://apache.org/xml/properties/schema/external-schemaLocation,它就可以工作。但是对于命名空间,我完全不知道该怎么办。

4

1 回答 1

0

我已经解决了。架构应该像这样开始:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://some/namespace/identifier"
    xmlns="http://some/namespace/identifier"
    elementFormDefault="qualified">

根开始标签是这样定义的:

<rootElement xmlns="http://some/namespace/identifier"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://some/namespace/identifier whatever.xsd">

最后我更新了我的代码:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
SchemaFactory scf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
URL schemaUrl = getClass().getResource(SCHEMAFILE);

dbf.setNamespaceAware(true);
dbf.setSchema(schema);

DocumentBuilder builder = dbf.newDocumentBuilder();
builder.setErrorHandler(errHandler);
Document doc = builder.parse(input);
于 2013-02-26T08:32:36.963 回答