下面列出了javax.xml.parsers.SAXParser#setProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static SAXParser allowFileAccess(SAXParser saxParser, boolean disableSecureProcessing) throws SAXException {
// if feature secure processing enabled, nothing to do, file is allowed,
// or user is able to control access by standard JAXP mechanisms
if (disableSecureProcessing) {
return saxParser;
}
try {
saxParser.setProperty(ACCESS_EXTERNAL_SCHEMA, "file");
LOGGER.log(Level.FINE, Messages.format(Messages.JAXP_SUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA));
} catch (SAXException ignored) {
// nothing to do; support depends on version JDK or SAX implementation
LOGGER.log(Level.CONFIG, Messages.format(Messages.JAXP_UNSUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA), ignored);
}
return saxParser;
}
private static SAXParser allowFileAccess(SAXParser saxParser, boolean disableSecureProcessing) throws SAXException {
// if feature secure processing enabled, nothing to do, file is allowed,
// or user is able to control access by standard JAXP mechanisms
if (disableSecureProcessing) {
return saxParser;
}
try {
saxParser.setProperty(ACCESS_EXTERNAL_SCHEMA, "file");
LOGGER.log(Level.FINE, Messages.format(Messages.JAXP_SUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA));
} catch (SAXException ignored) {
// nothing to do; support depends on version JDK or SAX implementation
LOGGER.log(Level.CONFIG, Messages.format(Messages.JAXP_UNSUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA), ignored);
}
return saxParser;
}
/**
* Test the default functionality of schema support method. In
* this case the schema source property is set.
* @throws Exception If any errors occur.
*/
@Test(dataProvider = "schema-source")
public void testCheckSchemaSupport3(Object schemaSource) throws Exception {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
W3C_XML_SCHEMA_NS_URI);
sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
DefaultHandler dh = new DefaultHandler();
// Not expect any unrecoverable error here.
sp.parse(new File(XML_DIR, "test1.xml"), dh);
} finally {
if (schemaSource instanceof Closeable) {
((Closeable) schemaSource).close();
}
}
}
private static SAXParser allowFileAccess(SAXParser saxParser, boolean disableSecureProcessing) throws SAXException {
// if feature secure processing enabled, nothing to do, file is allowed,
// or user is able to control access by standard JAXP mechanisms
if (disableSecureProcessing) {
return saxParser;
}
try {
saxParser.setProperty(ACCESS_EXTERNAL_SCHEMA, "file");
LOGGER.log(Level.FINE, Messages.format(Messages.JAXP_SUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA));
} catch (SAXException ignored) {
// nothing to do; support depends on version JDK or SAX implementation
LOGGER.log(Level.CONFIG, Messages.format(Messages.JAXP_UNSUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA), ignored);
}
return saxParser;
}
private static SAXParser newSAXParser(URL schema, InputStream schemaStream,
boolean loadExternalDtds) throws ParserConfigurationException, SAXException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
parserFactory.setValidating(canUseSchemaValidation && (schema != null));
if (!loadExternalDtds && canDisableExternalDtds(parserFactory)) {
parserFactory.setFeature(XERCES_LOAD_EXTERNAL_DTD, false);
}
SAXParser parser = parserFactory.newSAXParser();
if (canUseSchemaValidation && schema != null) {
try {
parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
parser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream);
} catch (SAXNotRecognizedException ex) {
Message.warn("problem while setting JAXP validating property on SAXParser... "
+ "XML validation will not be done", ex);
canUseSchemaValidation = false;
parserFactory.setValidating(false);
parser = parserFactory.newSAXParser();
}
}
parser.getXMLReader().setFeature(XML_NAMESPACE_PREFIXES, true);
return parser;
}
/**
* Create a <code>SAXParser</code> configured to support XML Scheman and DTD
* @param properties parser specific properties/features
* @return an XML Schema/DTD enabled <code>SAXParser</code>
*/
public static SAXParser newSAXParser(Properties properties)
throws ParserConfigurationException,
SAXException,
SAXNotRecognizedException{
SAXParserFactory factory =
(SAXParserFactory)properties.get("SAXParserFactory");
SAXParser parser = factory.newSAXParser();
String schemaLocation = (String)properties.get("schemaLocation");
String schemaLanguage = (String)properties.get("schemaLanguage");
try{
if (schemaLocation != null) {
parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
}
} catch (SAXNotRecognizedException e){
log.info(parser.getClass().getName() + ": "
+ e.getMessage() + " not supported.");
}
return parser;
}
/**
* Create a <code>SAXParser</code> configured to support XML Schema and DTD
* @param properties parser specific properties/features
* @return an XML Schema/DTD enabled <code>SAXParser</code>
*/
public static SAXParser newSAXParser(Properties properties)
throws ParserConfigurationException,
SAXException,
SAXNotRecognizedException{
SAXParserFactory factory =
(SAXParserFactory)properties.get("SAXParserFactory");
SAXParser parser = factory.newSAXParser();
String schemaLocation = (String)properties.get("schemaLocation");
String schemaLanguage = (String)properties.get("schemaLanguage");
try{
if (schemaLocation != null) {
parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
}
} catch (SAXNotRecognizedException e){
log.info(parser.getClass().getName() + ": "
+ e.getMessage() + " not supported.");
}
return parser;
}
private static SAXParser allowFileAccess(SAXParser saxParser, boolean disableSecureProcessing) throws SAXException {
// if feature secure processing enabled, nothing to do, file is allowed,
// or user is able to control access by standard JAXP mechanisms
if (disableSecureProcessing) {
return saxParser;
}
try {
saxParser.setProperty(ACCESS_EXTERNAL_SCHEMA, "file");
LOGGER.log(Level.FINE, Messages.format(Messages.JAXP_SUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA));
} catch (SAXException ignored) {
// nothing to do; support depends on version JDK or SAX implementation
LOGGER.log(Level.CONFIG, Messages.format(Messages.JAXP_UNSUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA), ignored);
}
return saxParser;
}
/**
* Configure the parser to allow access to DTDs on the file system.
*/
private static void enableFileAccess(SAXParser parser) throws SAXNotSupportedException {
try {
parser.setProperty("http://javax.xml.XMLConstants/property/accessExternalDTD", "file");
} catch (SAXNotRecognizedException ignore) {
// property requires >= JAXP 1.5
}
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
public void convert(Reader reader, OutputStream finf) throws Exception {
InputSource is = new InputSource(reader);
SAXParser saxParser = getParser();
SAXDocumentSerializer documentSerializer = getSerializer(finf);
saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", documentSerializer);
saxParser.parse(is, documentSerializer);
}
/**
* Test to set and get the declaration-handler.
*
* @param saxparser a SAXParser instance.
* @throws SAXException If any parse errors occur.
*/
@Test(dataProvider = "parser-provider")
public void testProperty06(SAXParser saxparser) throws SAXException {
MyDeclHandler myDeclHandler = new MyDeclHandler();
saxparser.setProperty(DECL_HANDLER, myDeclHandler);
assertTrue(saxparser.getProperty(DECL_HANDLER) instanceof DeclHandler);
}
protected static SAXParser createParser() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
return parser;
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
public void convert(Reader reader, OutputStream finf) throws Exception {
InputSource is = new InputSource(reader);
SAXParser saxParser = getParser();
SAXDocumentSerializer documentSerializer = getSerializer(finf);
saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", documentSerializer);
saxParser.parse(is, documentSerializer);
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
/**
* 通过XSD(XML Schema)校验XML
*/
@Test
public void validateXMLByXSD() {
String path = this.getClass().getResource("/").getPath();
int index = path.lastIndexOf("/");
path = path.substring(0, index);
String xmlFileName = path + "/processCore.xml";
// String xsdFileName =
// "/Users/user/workspace/bulbasaur/core/src/test/resources/process_bak.xsd";
String xsdFileName = path + "/test.xsd";
try {
// 创建默认的XML错误处理器
XMLErrorHandler errorHandler = new XMLErrorHandler();
// 获取基于 SAX 的解析器的实例
SAXParserFactory factory = SAXParserFactory.newInstance();
// 解析器在解析时验证 XML 内容。
factory.setValidating(true);
// 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
factory.setNamespaceAware(true);
// 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
SAXParser parser = factory.newSAXParser();
// 创建一个读取工具
SAXReader xmlReader = new SAXReader();
// 获取要校验xml文档实例
Document xmlDocument = xmlReader.read(new File(xmlFileName));
// 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在
// [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
// 创建一个SAXValidator校验工具,并设置校验工具的属性
SAXValidator validator = new SAXValidator(parser.getXMLReader());
// 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
validator.setErrorHandler(errorHandler);
// 校验
validator.validate(xmlDocument);
XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
// 如果错误信息不为空,说明校验失败,打印错误信息
if (errorHandler.getErrors().hasContent()) {
System.out.println("XML文件通过XSD文件校验失败!");
writer.write(errorHandler.getErrors());
} else {
System.out.println("Good! XML文件通过XSD文件校验成功!");
}
} catch (Exception ex) {
System.out.println("XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());
ex.printStackTrace();
}
}
@Test(expectedExceptions = SAXException.class)
public void testSchemaValidationNeg() throws Exception {
SAXParser sp = getValidatingParser();
sp.setProperty(JAXP_SCHEMA_SOURCE, "catalog.xsd");
sp.parse(new File(ASTROCAT), new DefaultHandler());
}