cvc-complex-type.3.2.2:属性xsi:不允许在Java DOM中出现schemaLocation
作者:互联网
我试图通过使用DOM验证器在Java中使用XSD验证我的XML.
虽然我手动地知道该文档确实有效,但DOM验证器还是对我说:
cvc-complex-type.3.2.2: Attribute <xsi:schemaLocation> is not allowed to appear in the element <people>
我已经确定:
setNamespaceAware()设置为true
schemaLanguage属性在schemaSource之前设置
schemaLanguage设置为http://ww.w3.org/2001/XMLSchema
XSD和XML都与.java和.class文件位于同一文件夹中
SSCCE
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
public class DOMValidator {
String xmlInstance = null;
String xmlSchema = null;
public static void main(String[] args){
DOMValidator validator = new DOMValidator();
validator.validateXML("student.xsd",
"helloWorld.xml");
}
public void validateXML(String xsd,String xml){
xmlSchema = xsd;
xmlInstance = xml;
beginValidation();
}
public void beginValidation(){
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
xmlSchema);
ErrorHandler errorHandler = new ErrorHandler();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(errorHandler);
builder.parse(xmlInstance);
if(errorHandler.errorOccured == true){
System.out.println("Document is Invalid.");
System.out.println(errorHandler.ex.getMessage());
}else{
System.out.println("Doument is valid");
}
}catch(ParserConfigurationException e){
e.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
private class ErrorHandler extends DefaultHandler{
public SAXParseException ex = null;
public boolean errorOccured = false;
@Override public void error(SAXParseException ex){
this.ex = ex;
errorOccured = true;
}
@Override public void fatalError(SAXParseException ex){
this.ex = ex;
errorOccured = true;
}
@Override public void warning(SAXParseException ex){
this.ex = ex;
errorOccured = true;
}
}
}
XSD
<xs:schema xmlns:xs="http://www.w3c.org/2001/XMLSchema"
xmlns="http://www.cmu.edu/ns/blank"
targetNamespace="http://www.cmu.edu/ns/blank"
elementFormDefault="qualified">
XML
<people
xmlns="http://www.cmu.edu/ns/blank"
xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.cmu.edu/ns/blank student.xsd">
我该如何解决这个问题?
解决方法:
问题出在这里:
<xs:schema xmlns:xs="http://www.w3c.org/2001/XMLSchema" .....>
和
<people
xmlns="http://www.cmu.edu/ns/blank"
xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"....>
问题是w3c.org中的c. DOM解析器希望它在任何地方都是w3.org–在XML文档中,在XML Schema Document中,在schemaLanguage和schemaSource属性中.
标签:jaxp,java,dom,xml,saxparseexception 来源: https://codeday.me/bug/20190729/1567611.html