我使用 Apache Commons XMLConfiguration 进行配置。现在我需要一个基于模式的验证。但我无法将我的 xsd 添加到 XMLConfiguration。xsd 位于应用程序 jar 文件中。
如果我使用 Java SE 中的方法,验证运行不会出现问题:
private void checkSchema(final Path path)
throws SAXException, ParserConfigurationException, IOException
{
final URL urlXsd = getClass().getResource(ConfigMain.SCHEMA_RESOURCE_PATH);
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = sf.newSchema(urlXsd);
final Validator validator = schema.newValidator();
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(path.toFile());
validator.validate(new DOMSource(doc));
}
但是,如果我将 XMLConfiguration 与 DefaultEntityResolver 一起使用,我就没有成功。
xmlConfig = new XMLConfiguration();
final URL urlXsd = getClass().getResource(SCHEMA_RESOURCE_PATH);
resolver.registerEntityId("configuration", urlXsd);
xmlConfig.setEntityResolver(resolver);
xmlConfig.setSchemaValidation(true);
我得到以下异常:
Caused by: org.xml.sax.SAXParseException; systemId: file:/C:/.../config_default.xml; lineNumber: 2; columnNumber: 16; cvc-elt.1: Cannot find the declaration of element 'configuration'.
“配置”是 config_default.xml 的根元素。我认为这意味着,它找不到 xsd。
我的第一个问题,我必须在 resolver.registerEntityId("configuration", urlXsd); 的第一个参数中输入什么?架构的公共 ID 是什么?该文档仅显示了一个带有 DTD public id 的示例。
这是简化的架构和 xml -> xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
</configuration>
架构:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"
<xs:element name="configuration">
</xs:element>
</xs:schema>
更新:我的测试基于 dbank 的回答:
package de.company.xmlschematest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class App
{
private final XMLConfiguration xmlConfig = new XMLConfiguration();
private static final Logger LOG = LoggerFactory.getLogger(App.class);
private static final String CONFIG_FILENAME_DEFAULT = "config_default.xml";
private static final String CONFIG_FILENAME_LOCAL =
"C:\\Data\\config_current.xml";
private static final Path CONFIG_PATH_LOCAL = Paths.get(
CONFIG_FILENAME_LOCAL);
private static final String SCHEMA_FILENAME = "config_schema.xsd";
/* package */ static final String SCHEMA_RESOURCE_PATH = "/" + SCHEMA_FILENAME;
private static final String CONFIG_DEFAULT_RESOURCE_PATH = "/" +
CONFIG_FILENAME_DEFAULT;
private static final org.apache.commons.logging.Log LOG_SEC = LogFactory.getLog(App.class);
public App()
{
try
{
LOG_SEC.debug("JCL");
xmlConfig.setLogger(LOG_SEC);
final URL urlXsd = getClass().getResource(SCHEMA_RESOURCE_PATH);
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = sf.newSchema(urlXsd);
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setSchema(schema);
final DocumentBuilder db = dbf.newDocumentBuilder();
xmlConfig.setDocumentBuilder(db);
xmlConfig.setSchemaValidation(true);
}
catch (SAXException | ParserConfigurationException ex)
{
LOG.error("Loading error", ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("XmlSchemaTest started");
final App app = new App();
app.loadConfig();
System.out.println("Finished");
}
private void loadConfig()
{
if(Files.exists(CONFIG_PATH_LOCAL))
{
try
{
xmlConfig.clear();
LOG.debug("Loading config {}", CONFIG_PATH_LOCAL);
xmlConfig.setFile(CONFIG_PATH_LOCAL.toFile());
xmlConfig.refresh();
LOG.info("Current config loaded");
}
catch (final ConfigurationException ex)
{
LOG.error("Loading of current config file has failed", ex);
loadDefault();
}
}
else
{
LOG.info("Local configuration is not available");
loadDefault();
}
}
private void loadDefault()
{
try
{
xmlConfig.clear();
LOG.debug("Loading config " + CONFIG_FILENAME_DEFAULT);
final File oldConfig = xmlConfig.getFile();
xmlConfig.setURL(getClass().getResource(
CONFIG_DEFAULT_RESOURCE_PATH));
if(oldConfig != null && oldConfig.exists())
{
oldConfig.delete();
}
xmlConfig.refresh();
xmlConfig.save(CONFIG_FILENAME_LOCAL);
LOG.info("Default config loaded");
}
catch (final ConfigurationException ex)
{
throw new IllegalStateException("The default config file is "
+ "not available", ex);
}
}
}
现在我用无效的 xml 对其进行了测试,但我只看到输出错误。没有抛出异常。
XmlSchemaTest started
18:23:16.263 [main] DEBUG de.company.xmlschematest.App - JCL
18:23:16.325 [main] DEBUG de.company.xmlschematest.App - Loading config C:\Data\config_current.xml
18:23:16.327 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
18:23:16.328 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
18:23:16.331 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
18:23:16.332 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
18:23:16.332 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
18:23:16.332 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
[Error] config_current.xml:29:21: cvc-complex-type.2.4.a: Invalid content was found starting with element 'number'. One of '{name}' is expected
18:23:16.356 [main] INFO de.company.xmlschematest.App - Current config loaded
Finished
更新 - xml 中 xsd 的路径: 我认为基于回调的处理不太好。根据您的第一个建议,我已经使用 xsd 的路径在 xml 中进行了测试。但这仅适用于任何路径。
package de.company.xmlschematest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* @author RD3
*/
public class App
{
private final XMLConfiguration xmlConfig = new XMLConfiguration();
private static final Logger LOG = LoggerFactory.getLogger(App.class);
private static final String CONFIG_FILENAME_DEFAULT = "config_default.xml";
private static final String CONFIG_FILENAME_LOCAL =
"C:\\Data\\config_current.xml";
private static final Path CONFIG_PATH_LOCAL = Paths.get(
CONFIG_FILENAME_LOCAL);
private static final String SCHEMA_FILENAME = "config_schema.xsd";
/* package */ static final String SCHEMA_RESOURCE_PATH = "/" + SCHEMA_FILENAME;
private static final String CONFIG_DEFAULT_RESOURCE_PATH = "/" +
CONFIG_FILENAME_DEFAULT;
private static final org.apache.commons.logging.Log LOG_SEC = LogFactory.getLog(App.class);
public App()
{
LOG_SEC.debug("JCL");
xmlConfig.setLogger(LOG_SEC);
xmlConfig.setSchemaValidation(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("XmlSchemaTest started");
final App app = new App();
app.loadConfig();
System.out.println("Finished");
}
private void loadConfig()
{
if(Files.exists(CONFIG_PATH_LOCAL))
{
try
{
xmlConfig.clear();
LOG.debug("Loading config {}", CONFIG_PATH_LOCAL);
xmlConfig.setFile(CONFIG_PATH_LOCAL.toFile());
xmlConfig.refresh();
LOG.info("Current config loaded");
}
catch (final ConfigurationException ex)
{
LOG.error("Loading of current config file has failed", ex);
loadDefault();
}
}
else
{
LOG.info("Local configuration is not available");
loadDefault();
}
}
private void loadDefault()
{
try
{
xmlConfig.clear();
LOG.debug("Loading config " + CONFIG_FILENAME_DEFAULT);
final File oldConfig = xmlConfig.getFile();
xmlConfig.setURL(getClass().getResource(
CONFIG_DEFAULT_RESOURCE_PATH));
if(oldConfig != null && oldConfig.exists())
{
oldConfig.delete();
}
xmlConfig.refresh();
xmlConfig.save(CONFIG_FILENAME_LOCAL);
LOG.info("Default config loaded");
}
catch (final ConfigurationException ex)
{
throw new IllegalStateException("The default config file is "
+ "not available", ex);
}
}
}
第一次运行确实处理正确。它从基于 xsi:noNamespaceSchemaLocation="config_schema.xsd" 的 jar 中获取 xsd。然后将从 jar 加载的默认配置写入本地文件系统。我检查了书面文件,找不到奇怪的想法。然后我再次运行示例应用程序,但现在出现以下错误:
XmlSchemaTest started
10:49:58.730 [main] DEBUG de.company.xmlschematest.App - JCL
10:49:58.738 [main] DEBUG de.company.xmlschematest.App - Loading config C:\Data\config_current.xml
10:49:58.740 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
10:49:58.741 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
10:49:58.744 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
10:49:58.745 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
10:49:58.745 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
10:49:58.746 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
10:49:58.795 [main] ERROR de.company.xmlschematest.App - Loading of current config file has failed
org.apache.commons.configuration.ConfigurationException: Error parsing file:/C:/Data/config_current.xml
at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:1014) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:972) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.XMLConfiguration$XMLFileConfigurationDelegate.load(XMLConfiguration.java:1647) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:324) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:261) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:238) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.refresh(AbstractFileConfiguration.java:889) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractHierarchicalFileConfiguration.refresh(AbstractHierarchicalFileConfiguration.java:335) ~[commons-configuration-1.10.jar:1.10]
at de.company.xmlschematest.App.loadConfig(App.java:110) [classes/:na]
at de.company.xmlschematest.App.main(App.java:68) [classes/:na]
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:379) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:605) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3138) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348) ~[na:1.8.0_31]
at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:1006) ~[commons-configuration-1.10.jar:1.10]
... 9 common frames omitted
10:49:58.796 [main] DEBUG de.company.xmlschematest.App - Loading config config_default.xml
10:49:58.862 [main] INFO de.company.xmlschematest.App - Default config loaded
Finished
他找不到xsd,但是xml文件中的路径是正确的,和第一次运行一样。为什么他在第一次玩的时候能找到 xsd,而在第二次运行时却找不到?
第二个问题,是 XMLConfiguration 的所有可能的日志输出吗?
更新 3:我再次测试并查看,如果我将 xsd 放入本地文件系统,那么第二次运行没有问题。我认为问题是在 xml 中定义路径时对 xsd 的相对搜索。
是否可以从本地文件系统加载 xml 并使用 jar 文件中的模式进行验证?我在调用 load() 或 refresh() 时搜索没有回调和直接异常处理的解决方案。
此致,