我正在尝试验证以下 XML
<query>
<colors logic="AND">
<color main="BLUE" tone="DARK" operator="=" />
</colors>
</query>
使用以下 XSD
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="color">
<xsd:attribute name="main" type="xsd:string" use="required"/>
<xsd:attribute name="tone" type="xsd:string" use="required"/>
<xsd:attribute name="operator" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="colors">
<xsd:sequence>
<xsd:element name="color" type="color" maxOccurs="unbounded"> </xsd:element>
</xsd:sequence>
<xsd:attribute name="logic" type="xsd:string" use="required"/>
</xsd:complexType>
<xsd:complexType name="query">
<xsd:sequence>
<xsd:element name="colors" type="colors" maxOccurs="2"></xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="query" type="query"></xsd:element>
</xsd:schema>
所以...我想验证没有任何命名空间的 XML。我无法更改 XML,因为它是由另一个应用程序生成的,我只想在服务器端保证客户端正在发送正确的请求。
当我尝试针对 XSD 验证 XML 时,我收到以下异常消息:
cvc-elt.1: Cannot find the declaration of element 'query'
解决方案(感谢@Traroth 为我指明了正确的方向)---
这是我验证它的方式:
我有这个功能:
public static Document buildValidRequest(String content, Schema xsd) throws SAXParseException, SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setSchema(xsd);
XMLSimpleErrorHandler errorHandler = new XMLSimpleErrorHandler();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(errorHandler);
StringReader reader = new StringReader(content);
Document validXML = builder.parse(new InputSource(reader));
if (errorHandler.getException() != null) {
throw errorHandler.getException();
}
return validXML;
}
这个类来处理错误:
public class XMLSimpleErrorHandler implements ErrorHandler {
private SAXParseException exception;
@Override
public void warning(SAXParseException e) {
this.exception = e;
}
@Override
public void error(SAXParseException e) {
this.exception = e;
}
@Override
public void fatalError(SAXParseException e) {
this.exception = e;
}
public SAXParseException getException() {
return exception;
}
}
而这种获取模式的方法:
private static Schema getSchema(String xsdPath) throws SAXException, IOException {
InputStream resourceAsStream = null;
try {
ServiceManager.getInstance().getLoggerManager().debug(RESTInitServlet.LOGCONTEXT, TAG, "Retrieving schema: "+xsdPath);
resourceAsStream = getInstance().getClass().getResourceAsStream(xsdPath);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSource = new StreamSource(resourceAsStream);
Schema schema = schemaFactory.newSchema(schemaSource);
return schema;
} finally {
if (resourceAsStream != null) {
resourceAsStream.close();
}
}
}
没关系:最奇怪的是:适用于在 Windows 7 上运行的 Tomcat 6;不能在 Linux 上运行的 jboss 中工作......