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

  1. 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:

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <student id="10">
  3. <age>12</age>
  4. <name>Malik</name>
  5. </student>

The following example shows the usage of Javax.xml.parsers.DocumentBuilder.setEntityResolver()method.

  1. package com.tutorialspoint;
  2.  
  3. import javax.xml.parsers.DocumentBuilder;
  4. import javax.xml.parsers.DocumentBuilderFactory;
  5. import org.w3c.dom.Document;
  6. import org.w3c.dom.Element;
  7. import org.w3c.dom.NodeList;
  8. import org.xml.sax.EntityResolver;
  9. import org.xml.sax.InputSource;
  10.  
  11. // an EntityResolver for our builder.
  12. class Resolver implements EntityResolver {
  13.  
  14. public InputSource resolveEntity(String publicId, String systemId) {
  15. System.out.println(publicId);
  16. System.out.println(systemId);
  17. if (systemId.equals("")) {
  18. System.out.println("Resolving Entity...");
  19. return null;
  20. } else {
  21. // use the default behaviour
  22. return null;
  23. }
  24. }
  25. }
  26.  
  27. public class DocumentBuilderDemo {
  28.  
  29. public static void main(String[] args) {
  30.  
  31. // create a new DocumentBuilderFactory
  32. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  33.  
  34. try {
  35. // use the factory to create a documentbuilder
  36. DocumentBuilder builder = factory.newDocumentBuilder();
  37.  
  38. Resolver res = new Resolver();
  39. builder.setEntityResolver(res);
  40.  
  41. // create a new document from input stream and an empty systemId
  42. Document doc = builder.parse("Student.xml");
  43.  
  44. // get the first element
  45. Element element = doc.getDocumentElement();
  46.  
  47. // get all child nodes
  48. NodeList nodes = element.getChildNodes();
  49.  
  50. // print the text content of each child
  51. for (int i = 0; i < nodes.getLength(); i++) {
  52. System.out.println("" + nodes.item(i).getTextContent());
  53. }
  54.  
  55. } catch (Exception ex) {
  56. ex.printStackTrace();
  57. }
  58. }
  59. }

为什么要设置EntityResolver呢?在解析的时候如果xml文件不符合xsd文件的要求则会报错误,从而终止解析,其实跟下面的一样效果的

  1. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  2. factory.setValidating(false);
  3. factory.setNamespaceAware(true);
  4.  
  5. SchemaFactory schemaFactory =
  6. SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  7.  
  8. factory.setSchema(schemaFactory.newSchema(
  9. new Source[] {new StreamSource("contacts.xsd")}));
  10.  
  11. DocumentBuilder builder = factory.newDocumentBuilder();
  12.  
  13. builder.setErrorHandler(new SimpleErrorHandler());
  14.  
  15. Document document = builder.parse(new InputSource("document.xml"));
  1. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  2. factory.setValidating(true);
  3. factory.setNamespaceAware(true);
  4.  
  5. DocumentBuilder builder = factory.newDocumentBuilder();
  6.  
  7. builder.setErrorHandler(new SimpleErrorHandler());
  8.  
  9. Document document = builder.parse(new InputSource("document.xml"));

现在问题来了,如果要使用外部的dtd文件校验的话怎么办?

问题提出 :

解析ejb-jar.xml,出现在网络连不上的情况下,解析失败的情况。

问题分析:

我们使用的是DOM进行XML的解析的:

  1. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  2. DocumentBuilder builder = factory.newDocumentBuilder();
  3.  
  4. //位置点
  5.  
  6. Document doc = builder.parse(file);

由于ejb-jar.xml中,有

  1. <!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:

  1. builder.setEntityResolver(
  2. new EntityResolver(){
  3. public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
  4. {
  5. return new InputSource(new StringBufferInputStream(""));
  6. // return null;//这个的效果仍然是从网络来抓取DTD来验证
  7. }
  8. }
  9. );

上面的设置就不会对XML文件进行验证。

如果一定要验证的话,我们也可以设置使用本地的DTD文件来做验证:

  1. builder.setEntityResolver(
  2. new EntityResolver(){
  3. public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
  4. {
  5. if(publicId.equals("-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"))
  6. {
  7. String dtd_uri = "C:/TEMP/ejb-jar_2_0.dtd";
  8. return new InputSource(dtd_uri);
  9. }
  10. }
  11. );

注意:直接return null,仍然会从网络来抓取DTD来验证。

所以这也是spring为什么采用设置setEntityResolver来校验xml格式的方式的原因

DocumentBuilder setEntityResolver() Method的更多相关文章

  1. 【死磕 Spring】----- IOC 之 获取 Document 对象

    原文出自:http://cmsblogs.com 在 XmlBeanDefinitionReader.doLoadDocument() 方法中做了两件事情,一是调用 getValidationMode ...

  2. Android学习笔记之DocumentBuilder的使用....

    PS:当你的才华还撑不起你的野心时,那你需要静下心来学习..... 学习内容: 1.从服务器上获取XML文档... 2.解析XML文档中的内容...   XML文件想必大家都非常的熟悉,可扩展的标记语 ...

  3. LIRe 源代码分析 4:建立索引(DocumentBuilder)[以颜色布局为例]

    ===================================================== LIRe源代码分析系列文章列表: LIRe 源代码分析 1:整体结构 LIRe 源代码分析 ...

  4. LIRe 源代码分析 2:基本接口(DocumentBuilder)

    ===================================================== LIRe源代码分析系列文章列表: LIRe 源代码分析 1:整体结构 LIRe 源代码分析 ...

  5. jsp中出现onclick函数提示Cannot return from outside a function or method

    在使用Myeclipse10部署完项目后,原先不出错的项目,会有红色的叉叉,JSP页面会提示onclick函数错误 Cannot return from outside a function or m ...

  6. 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 ...

  7. 设计模式(九): 从醋溜土豆丝和清炒苦瓜中来学习"模板方法模式"(Template Method Pattern)

    今天是五.四青年节,祝大家节日快乐.看着今天这标题就有食欲,夏天到了,醋溜土豆丝和清炒苦瓜适合夏天吃,好吃不上火.这两道菜大部分人都应该吃过,特别是醋溜土豆丝,作为“鲁菜”的代表作之一更是为大众所熟知 ...

  8. 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 ...

  9. IIS7.5上的REST服务的Put,Delete操作发生HTTP Error 405.0 - Method Not Allowed 解决方法

    WebDAV 是超文本传输协议 (HTTP) 的一组扩展,为 Internet 上计算机之间的编辑和文件管理提供了标准.利用这个协议用户可以通过Web进行远程的基本文件操作,如拷贝.移动.删除等.在I ...

随机推荐

  1. js小分享

    之前实现一些js代码时,总觉得无法下手,所以最近在学习一下特别细的知识点,分享笔记.嘻嘻,偷个小懒,我把自己的笔记拍个照片就不打字了.嘎嘎,放心放心,自觉得字写的还算ok的啦- 表示家里的老弟玩游戏, ...

  2. QT UI 使一个QWidget里面的元素自动填充满本QWidget

    使一个QWidget里面的元素自动填充满本QWidget: 对象查看器,右键点击本QWidget,选择"布局",为此QWidget增加一个布局. 如果该QWidget只有一个对象, ...

  3. html本地存储尝试

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. Windows phone 之Interaction.Triggers的使用

    两个步骤:1.添加以下两个程序集System.Windows.InteractivityMicrosoft.Expression.Interactions 2.添加xmlns:i="clr- ...

  5. JavaScript学习总结【5】、JS DOM

    1.DOM 简介 当页面加载时,浏览器会创建页面的文档对象模型(Document Object Model).文档对象模型定义访问和处理 HTML 文档的标准方法.DOM 将 HTML 文档呈现为带有 ...

  6. ibatis面试笔记

    ibatis是在结果集与实体类之间进行映射hibernate是在数据库与实体类之间进行映射Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序 ...

  7. 网站商务通链接快速标识v1.0.js

    js代码为: function getSwt(keys){ try{ if(openZoosUrl&&typeof(openZoosUrl)=="function" ...

  8. git 创建多个账户ssh

    创建一个账户 创建ssh本地秘钥. $ ssh-keygen -t rsa -C "youremail@xxx.com" 一路回车,会在~/.ssh/目录下生成id_rsa和id_ ...

  9. 《C和指针》章节后编程练习解答参考——6.4

    <C和指针>——6.4 题目: 质数是只能被1和本身整除的整数. 在1到1000之间的质数,在数组中剔除不是质数的数. 解答代码: #include <stdio.h> #de ...

  10. 关于64位Win7/Win 8 下怎么学习汇编语言

    我看有许多同学用Win 7/Win 8 学习汇编,现在好多人的内存升级了都用64位系统了,但是64位W7没有自带的DEBUG和MASM. 1.首先下载DOSBOX,(下面附带地址)它的作用就是让你在6 ...