public static InputStream getResourceAsStream(String name)
throws IOException {
InputStream in = XMLUtil.class.getResourceAsStream(name);
if (in == null)
throw new FileNotFoundException(name);
return in;
}
然后,使用 SchemaFactory 实例通过 newSchema() 方法获取 Schema 对象:
import javax.xml.validation.*;
...
public static Schema newSchema(String name)
throws IOException, SAXException {
Schema schema;
InputStream in = getResourceAsStream(name);
try{
schema = schemaFactory.newSchema(new StreamSource(in));
}finally{
in.close();
}
return schema;
}
您还可以使用以下方法创建 Oracle XMLSchema 对象:
import oracle.xml.parser.schema.XMLSchema;
import oracle.xml.parser.schema.XSDBuilder;
...
public static XMLSchema newOracleSchema(String name)
throws IOException, SAXException {
XMLSchema schema;
InputStream in = getResourceAsStream(name);
try{
XSDBuilder builder = new XSDBuilder();
schema = builder.build(new InputSource(in));
} catch (Exception e){
throw new SAXException(e);
}finally{
in.close();
}
return schema;
}
接下来,您需要创建一个 DocumentBuilderFactory。如果在 CLASSPATH 中找到的是 JAXP 1.1 实现,则由 JAXP 1.2 定义的 setSchema() 方法可能会抛出 UnsupportedOperationException,此时需要将 JAXP 1.1 实现替换为 Java SE 5.0 的 JAXP 1.2 实现。在这种情况下,您仍可使用 newOracleSchema() 创建模式对象,并通过 setAttribute()方法对其进行设置:
import javax.xml.parsers.*;
import oracle.xml.jaxp.JXDocumentBuilderFactory;
...
public static DocumentBuilderFactory newParserFactory(
String schemaName) throws IOException, SAXException {
DocumentBuilderFactory parserFactory
= DocumentBuilderFactory.newInstance();
try{
parserFactory.setSchema(newSchema(schemaName));
} catch (UnsupportedOperationException e) {
if (parserFactory instanceof JXDocumentBuilderFactory) {
parserFactory.setAttribute(
JXDocumentBuilderFactory.SCHEMA_OBJECT,
newOracleSchema(schemaName));
}
}
return parserFactory;
}
然后,创建一个 DocumentBuilder 对象,并使用该对象验证和分析 XML 文档:
import javax.xml.parsers.*;
...
public static DocumentBuilder newParser(
DocumentBuilderFactory parserFactory)
throws ParserConfigurationException {
DocumentBuilder parser = parserFactory.newDocumentBuilder();
parser.setErrorHandler(newErrorHandler());
return parser;
};
假设您要根据 portfolio.xsd 模式示例验证 XML 文档:
< xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
< xsd:element name="portfolio" type="portfolioType"
< xsd:complexType name="portfolioType">
< xsd:sequence>
< xsd:element name="stock"
minOccurs="0" maxOccurs="unbounded">
< xsd:complexType>
< xsd:attribute name="symbol"
type="xsd:string" use="required"/>
< xsd:attribute name="shares"
type="xsd:positiveInteger" use="required"/>
< xsd:attribute name="paidPrice"
type="xsd:decimal" use="required"/>
< /xsd:complexType>
< /xsd:element>
< /xsd:sequence>
< /xsd:co
