DocumentBuilder setEntityResolver() Method
Description
The Javax.xml.parsers.DocumentBuilder.setEntityResolver(EntityResolver er) method specifies the EntityResolver to be used to resolve entities present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it's own default implementation and behavior.
Declaration
Following is the declaration for Javax.xml.parsers.DocumentBuilder.setEntityResolver() method
public abstract void setEntityResolver(EntityResolver er)
Parameters
er -- The EntityResolver to be used to resolve entities present in the XML document to be parsed.
Return Value
This method does not return a value.
Exception
NA
Example
For our examples to work, a xml file named Student.xml is needed in our CLASSPATH. The contents of this XML are the following:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="10">
<age>12</age>
<name>Malik</name>
</student>
The following example shows the usage of Javax.xml.parsers.DocumentBuilder.setEntityResolver()method.
package com.tutorialspoint; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource; // an EntityResolver for our builder.
class Resolver implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) {
System.out.println(publicId);
System.out.println(systemId);
if (systemId.equals("")) {
System.out.println("Resolving Entity...");
return null;
} else {
// use the default behaviour
return null;
}
}
} public class DocumentBuilderDemo { public static void main(String[] args) { // create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try {
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder(); Resolver res = new Resolver();
builder.setEntityResolver(res); // create a new document from input stream and an empty systemId
Document doc = builder.parse("Student.xml"); // get the first element
Element element = doc.getDocumentElement(); // get all child nodes
NodeList nodes = element.getChildNodes(); // print the text content of each child
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("" + nodes.item(i).getTextContent());
} } catch (Exception ex) {
ex.printStackTrace();
}
}
}
为什么要设置EntityResolver呢?在解析的时候如果xml文件不符合xsd文件的要求则会报错误,从而终止解析,其实跟下面的一样效果的
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true); SchemaFactory schemaFactory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(
new Source[] {new StreamSource("contacts.xsd")})); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new SimpleErrorHandler()); Document document = builder.parse(new InputSource("document.xml"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new SimpleErrorHandler()); Document document = builder.parse(new InputSource("document.xml"));
现在问题来了,如果要使用外部的dtd文件校验的话怎么办?
问题提出 :
解析ejb-jar.xml,出现在网络连不上的情况下,解析失败的情况。
问题分析:
我们使用的是DOM进行XML的解析的:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder(); //位置点 Document doc = builder.parse(file);
由于ejb-jar.xml中,有
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
在解析的时候,会从网络http://java.sun.com/dtd/ejb-jar_2_0.dtd中抓紧DTD文件,进行验证,如果网络不通,那么就会出现解析失败。
首先,DocumentBuilderFactory.newInstance()创建DocumentBuilderFactory实现类的对象,它会通过一下方式来查找实现类:
1.在系统环境变量中(System.getProperties())中查找 key=javax.xml.parsers.DocumentBuilderFactory
2.如果1没有找到,则找java.home\lib\jaxp.properties 文件,如果文件存在,在文件中查找key=javax.xml.parsers.DocumentBuilderFactory
3.如果2没有找到,则在classpath中的所有的jar包中查找META-INF/services /javax.xml.parsers.DocumentBuilderFactory 文件
全都没找到,则返回null
如果上面都没有找到,那么就使用JDK自带的实现类:
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
在创建DocumentBuilder实例的时候,是根据DocumentBuilderFactoryImpl的不同有不同的实现。
为了在网络不可用的情况下,正常解析XML文件,我们可以在使用builder之前,设置EntityResolver:
builder.setEntityResolver(
new EntityResolver(){
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
{
return new InputSource(new StringBufferInputStream(""));
// return null;//这个的效果仍然是从网络来抓取DTD来验证
}
}
);
上面的设置就不会对XML文件进行验证。
如果一定要验证的话,我们也可以设置使用本地的DTD文件来做验证:
builder.setEntityResolver(
new EntityResolver(){
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
{
if(publicId.equals("-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"))
{
String dtd_uri = "C:/TEMP/ejb-jar_2_0.dtd";
return new InputSource(dtd_uri);
}
}
);
注意:直接return null,仍然会从网络来抓取DTD来验证。
所以这也是spring为什么采用设置setEntityResolver来校验xml格式的方式的原因
DocumentBuilder setEntityResolver() Method的更多相关文章
- 【死磕 Spring】----- IOC 之 获取 Document 对象
原文出自:http://cmsblogs.com 在 XmlBeanDefinitionReader.doLoadDocument() 方法中做了两件事情,一是调用 getValidationMode ...
- Android学习笔记之DocumentBuilder的使用....
PS:当你的才华还撑不起你的野心时,那你需要静下心来学习..... 学习内容: 1.从服务器上获取XML文档... 2.解析XML文档中的内容... XML文件想必大家都非常的熟悉,可扩展的标记语 ...
- LIRe 源代码分析 4:建立索引(DocumentBuilder)[以颜色布局为例]
===================================================== LIRe源代码分析系列文章列表: LIRe 源代码分析 1:整体结构 LIRe 源代码分析 ...
- LIRe 源代码分析 2:基本接口(DocumentBuilder)
===================================================== LIRe源代码分析系列文章列表: LIRe 源代码分析 1:整体结构 LIRe 源代码分析 ...
- jsp中出现onclick函数提示Cannot return from outside a function or method
在使用Myeclipse10部署完项目后,原先不出错的项目,会有红色的叉叉,JSP页面会提示onclick函数错误 Cannot return from outside a function or m ...
- Apply Newton Method to Find Extrema in OPEN CASCADE
Apply Newton Method to Find Extrema in OPEN CASCADE eryar@163.com Abstract. In calculus, Newton’s me ...
- 设计模式(九): 从醋溜土豆丝和清炒苦瓜中来学习"模板方法模式"(Template Method Pattern)
今天是五.四青年节,祝大家节日快乐.看着今天这标题就有食欲,夏天到了,醋溜土豆丝和清炒苦瓜适合夏天吃,好吃不上火.这两道菜大部分人都应该吃过,特别是醋溜土豆丝,作为“鲁菜”的代表作之一更是为大众所熟知 ...
- HTTP Method详细解读(`GET` `HEAD` `POST` `OPTIONS` `PUT` `DELETE` `TRACE` `CONNECT`)
前言 HTTP Method的历史: HTTP 0.9 这个版本只有GET方法 HTTP 1.0 这个版本有GET HEAD POST这三个方法 HTTP 1.1 这个版本是当前版本,包含GET HE ...
- IIS7.5上的REST服务的Put,Delete操作发生HTTP Error 405.0 - Method Not Allowed 解决方法
WebDAV 是超文本传输协议 (HTTP) 的一组扩展,为 Internet 上计算机之间的编辑和文件管理提供了标准.利用这个协议用户可以通过Web进行远程的基本文件操作,如拷贝.移动.删除等.在I ...
随机推荐
- jQuery noConflict() 方法
如何在页面上同时使用 jQuery 和其他框架? jQuery 和其他 JavaScript 框架 正如您已经了解到的,jQuery 使用 $ 符号作为 jQuery 的简写. 如果其他 JavaSc ...
- 初尝 MVC4
文章内容参考 http://www.cnblogs.com/leoo2sk/archive/2008/10/27/1320285.html 开发环境 VS2010 ,VS2010 开发 MVC4 需下 ...
- STUN/TURN/ICE协议在P2P SIP中的应用(二)
1 说明 2 打洞和穿越的概念... 1 3 P2P中的打洞和穿越... 2 4 使用STUN系列 协议穿越的特点... 2 5 STUN/ ...
- angularjs应用骨架(2)
时隔一个星期,接着上一篇的angularjs应用骨架继续聊聊angularjs其他的其他的内容. 区分UI和控制器的职责 在应用控制器中有三种职责: 1.为应用中模型设置初始状态 2.通过$scope ...
- 【实习记】2014-08-23网络安全XSS与CSRF总结
XSS:脚本中的不速之客XSS:跨站脚本(Cross-site scripting)CSRF:冒充用户之手CSRF:跨站请求伪造(Cross-site request forgery) 谷歌搜 ...
- php利用时间生成随机函数
date("YmdHis",time()); rand(); 生成随机数 当括号内无参数时 系统会以当前时间为种子进行随机数的生成 rand(1,10); 括号里面是生 ...
- [转] 《高性能HTML5》读后整理的Web性能优化内容
读后感 先说说<高性能HTML5>这本书的读后感吧,个人觉得这本书前两章跟书的标题完全搭不上关系,或者说只能算是讲解了“高性能”这三个字,HTML5完全不见踪影.个人觉得作者应该首先把HT ...
- php的几个版本的区别?
1. VC6与VC9的区别:VC6版本是使用Visual Studio 6编译器编译的,如果你的PHP是用Apache来架设的,那你就选择VC6版本.VC9版本是使用Visual Studio 200 ...
- 用VS2010编写的C++程序,在其他电脑上无法运行,提示缺少mfc100.dll的解决办法
问题: 在自己电脑上用VS2010编写的VC++程序(使用MFC库),不能在其他电脑上运行.双击提示: "无法启动此程序,因为计算机中丢失mfc100.dll 尝试重新安装该程序以解决此问题 ...
- 简单易学的机器学习算法——EM算法
简单易学的机器学习算法——EM算法 一.机器学习中的参数估计问题 在前面的博文中,如“简单易学的机器学习算法——Logistic回归”中,采用了极大似然函数对其模型中的参数进行估计,简单来讲即对于一系 ...