我有一个简单的 XSD 和一个更简单的 XML。但是 Java 2 XML 验证失败。(使用 javax.xml.validation)
这是我的 XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://foo.com/darnit"
targetNamespace="http://foo.com/darnit">
<xsd:element name="Person" type="tns:PersonType"/>
<xsd:simpleType name="nameType">
<xsd:restriction base="xsd:string"/>
</xsd:simpleType>
<xsd:complexType name="PersonType">
<xsd:sequence>
<xsd:element minOccurs="1" maxOccurs="2" name="FirstName" type="tns:nameType"/>
<xsd:element minOccurs="1" maxOccurs="1" name="LastName" type="tns:nameType"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
这是示例 XML:
<?xml version="1.0" encoding="UTF-8"?>
<Person xmlns="http://foo.com/darnit">
<FirstName>John</FirstName>
<FirstName>Michael</FirstName>
<LastName>Smith</LastName>
</Person>
这是我收到的错误消息:
org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'FirstName'. One of '{FirstName}' is expected.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.reportSchemaError(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.jaxp.validation.StreamValidatorHelper.validate(Unknown Source)
at org.apache.xerces.jaxp.validation.XMLSchemaValidator.validate(Unknown Source)
at javax.xml.validation.Validator.validate(Unknown Source)
如果我用命名空间前缀限定 XML,它就可以工作!
<?xml version="1.0" encoding="UTF-8"?>
<foo:Person xmlns:foo="http://foo.com/darnit">
<FirstName>John</FirstName>
<FirstName>Michael</FirstName>
<LastName>Smith</LastName>
</foo:Person>
但是我的 XSD 允许不合格的元素!
我是否必须在 SchemaFactory、Schema 或 Validator 上设置属性?
谢谢。