我有一个schema.xsd
,其中包含并修改xhtml,如下所示:
<xs:redefine schemaLocation="http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd">
...
</xs:redefine>
现在我写了一个验证器,
它工作正常,因为它不从网络加载任何文件,而是找到我的catalog.xml
文件中给出的xhtml11.xsd。
public class XmlTemplateValidator implements TemplateValidator
{
public List<SAXParseException> validate ( String xml ) throws Exception
{
Reader input = new StringReader(xml);
InputSource inputSource = new InputSource(input);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
XMLReader reader = parser.getXMLReader();
reader.setEntityResolver(new CatalogResolver());
DefaultErrorHandler handler = new DefaultErrorHandler();
reader.setErrorHandler(handler);
reader.parse(inputSource);
return handler.getSaxParseExceptions();
}
}
现在我想要完全相同的东西,但我想在我的验证器中给出架构(所以不要让作者说它应该验证哪个架构,而是让验证器决定使用哪个架构。
public class NewXmlTemplateValidator implements TemplateValidator
{
static final String schemaSource = "schema.xsd";
public List<SAXParseException> validate ( String xml ) throws Exception
{
Reader input = new StringReader(xml);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaUrl = getClass().getResource(schemaSource);
Schema schema = factory.newSchema(schemaUrl);
Validator validator = schema.newValidator();
DefaultErrorHandler handler = new DefaultErrorHandler();
validator.setErrorHandler(handler);
Source source = new StreamSource(input);
validator.validate(source);
return handler.getSaxParseExceptions();
}
}
它有效,但它确实从网络加载所有xhtml文件,这需要相当长的时间,而不是我想要的。
所以我想根据预定义的模式验证XML String,并通过catalog.xml定义进行适当的实体解析。
如何轻松地将CatalogResolver添加到第二个设置?
答案 0 :(得分:8)
在第二个示例中添加XMLCatalogResolver,如下所示:
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaUrl = getClass().getResource(schemaSource);
String catalog = getClass().getResource("/catalog.xml").getFile();
XMLCatalogResolver resolver = new XMLCatalogResolver(new String[] { catalog });
factory.setResourceResolver(resolver);