我遵循两个架构。 Master.xsd和Child.xsd
当我尝试使用Master.xsd验证xml时,我收到错误
org.xml.sax.SAXParseException:src-resolve:无法将名称'author'解析为(n)'元素声明'组件。
我也尝试在master.xsd中使用,这次我得到类似的错误:
org.xml.sax.SAXParseException:src-resolve:无法将名称'pub:author'解析为(n)'元素声明'组件。
虽然这已成功通过XMLSpy验证。
以下是架构,调用代码和验证码:
Master.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:pub="http://schema.abc.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://schema.abc.com">
<xs:import schemaLocation="Child.xsd"/>
<xs:element name="books">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="pub:book"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element ref="pub:published_date"/>
<xs:element ref="author"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="published_date" type="xs:dateTime"/>
</xs:schema>
Child.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="author">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="first_name"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="first_name" type="xsd:string"/>
</xsd:schema>
需要验证的Sample.xml:
<?xml version="1.0" encoding="UTF-8"?>
<pub:books xsi:schemaLocation="http://schema.abc.com" xmlns:pub="http://schema.abc.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<pub:book>
<pub:published_date>2001-12-17T09:30:47Z</pub:published_date>
<author>
<first_name>Adi</first_name>
</author>
</pub:book>
</pub:books>
验证的Java代码:
private void validate(final String schema, final String xml) {
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
InputStream is = getClass().getResourceAsStream(schema);
Schema schema;
try {
schema = schemaFactory.newSchema(new StreamSource(is));
Validator validator = schema.newValidator();
Source xmlSource = new StreamSource( new StringReader(xml));
validator.validate(xmlSource);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
调用代码:
validate(masterXSDPath, "xmlString");
请告诉我哪里出错?
答案 0 :(得分:2)
我想你会想要两种模式,比如:
schemaFactory.newSchema(new Source[]{new StreamSource(is1), new StreamSource(is2)});
或者,您可以为SchemaFactory提供自定义LSResourceResolver。
答案 1 :(得分:2)
通过实现LSResourceResolver修复它。 找不到Child.xsd。