Dom4j读取xml:
eg1:

  1. package xml;
  2.  
  3. import java.io.File;
  4.  
  5. import org.dom4j.DocumentException;
  6. import org.dom4j.io.SAXReader;
  7.  
  8. public class XmlReader_Dom4j {
  9. public static void main(String[] args) {
  10. String path = "D:\\test\\中文文件夹名\\namespaces.xml";
  11. readXml(path);//will throw exception
  12. File xmlFile=new File(path);
  13. readXml(xmlFile);
  14. path = "D:\\test\\path withWhiteSpace\\namespaces.xml";
  15. readXml(path);
  16.  
  17. path = "D:\\test\\normal\\namespaces.xml";
  18. readXml(path);
  19. }
  20.  
  21. private static void readXml(String path) {
  22. SAXReader saxReader=new SAXReader();
  23. try {
  24. saxReader.read(path);
  25. System.out.println("success");
  26. } catch (DocumentException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30.  
  31. private static void readXml(File xmlFile) {
  32. SAXReader saxReader=new SAXReader();
  33. try {
  34. saxReader.read(xmlFile);
  35. System.out.println("success");
  36. } catch (DocumentException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40.  
  41. }

Output:

  1. org.dom4j.DocumentException: unknown protocol: d Nested exception: unknown protocol: d
  2. at org.dom4j.io.SAXReader.read(SAXReader.java:484)
  3. at org.dom4j.io.SAXReader.read(SAXReader.java:321)
  4. at xml.XmlReader_Dom4j.readXml(XmlReader_Dom4j.java:24)
  5. at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:11)
  6. Nested exception:
  7. java.net.MalformedURLException: unknown protocol: d
  8. at java.net.URL.<init>(Unknown Source)
  9. at java.net.URL.<init>(Unknown Source)
  10. at java.net.URL.<init>(Unknown Source)
  11. at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
  12. at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
  13. at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
  14. at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
  15. at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
  16. at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
  17. at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
  18. at org.dom4j.io.SAXReader.read(SAXReader.java:465)
  19. at org.dom4j.io.SAXReader.read(SAXReader.java:321)
  20. at xml.XmlReader_Dom4j.readXml(XmlReader_Dom4j.java:24)
  21. at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:11)
  22. Nested exception: java.net.MalformedURLException: unknown protocol: d
  23. at java.net.URL.<init>(Unknown Source)
  24. at java.net.URL.<init>(Unknown Source)
  25. at java.net.URL.<init>(Unknown Source)
  26. at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
  27. at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
  28. at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
  29. at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
  30. at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
  31. at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
  32. at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
  33. at org.dom4j.io.SAXReader.read(SAXReader.java:465)
  34. at org.dom4j.io.SAXReader.read(SAXReader.java:321)
  35. at xml.XmlReader_Dom4j.readXml(XmlReader_Dom4j.java:24)
  36. at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:11)
  37. success
  38. success
  39. success

Source code:

  1. /**
  2. * <p>
  3. * Reads a Document from the given URL or filename using SAX.
  4. * </p>
  5. *
  6. * <p>
  7. * If the systemId contains a <code>':'</code> character then it is
  8. * assumed to be a URL otherwise its assumed to be a file name. If you want
  9. * finer grained control over this mechansim then please explicitly pass in
  10. * either a {@link URL}or a {@link File}instance instead of a {@link
  11. * String} to denote the source of the document.
  12. * </p>
  13. *
  14. * @param systemId
  15. * is a URL for a document or a file name.
  16. *
  17. * @return the newly created Document instance
  18. *
  19. * @throws DocumentException
  20. * if an error occurs during parsing.
  21. */
  22. public Document read(String systemId) throws DocumentException {
  23. InputSource source = new InputSource(systemId);
  24. if (this.encoding != null) {
  25. source.setEncoding(this.encoding);
  26. }
  27.  
  28. return read(source);
  29. }

eg2:

  1. private static void testWithUrl() throws MalformedURLException {
  2. System.out.println("=============testWithUrlBegin=============");
  3.  
  4. String path = "file:///D:\\test\\中文文件夹名\\namespaces.xml";
  5. newUrl(path);
  6. readXml(path);
  7.  
  8. path = "D:\\test\\中文文件夹名\\namespaces.xml";
  9. newUrl(path);
  10.  
  11. System.out.println("=============testWithUrlEnd=============");
  12. }
  13.  
  14. private static void newUrl(String path) throws MalformedURLException {
  15. try {
  16. new URL(path);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21.  
  22. private static void readXml(String path) {
  23. SAXReader saxReader=new SAXReader();
  24. try {
  25. Document document=saxReader.read(path);
  26. System.out.println("document.hasContent():"+document.hasContent());
  27. System.out.println("success");
  28. } catch (DocumentException e) {
  29. e.printStackTrace();
  30. }
  31. }

Output:

  1. =============testWithUrlBegin=============
  2. document.hasContent():true
  3. success
  4. java.net.MalformedURLException: unknown protocol: d
  5. at java.net.URL.<init>(Unknown Source)
  6. at java.net.URL.<init>(Unknown Source)
  7. at java.net.URL.<init>(Unknown Source)
  8. at xml.XmlReader_Dom4j.newUrl(XmlReader_Dom4j.java:50)
  9. at xml.XmlReader_Dom4j.testWithUrl(XmlReader_Dom4j.java:43)
  10. at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:13)
  11. =============testWithUrlEnd=============

saxReader.read(xmlFile)不报错的原因:

  1. /**
  2. * <p>
  3. * Reads a Document from the given <code>File</code>
  4. * </p>
  5. *
  6. * @param file
  7. * is the <code>File</code> to read from.
  8. *
  9. * @return the newly created Document instance
  10. *
  11. * @throws DocumentException
  12. * if an error occurs during parsing.
  13. */
  14. public Document read(File file) throws DocumentException {
  15. try {
  16. /*
  17. * We cannot convert the file to an URL because if the filename
  18. * contains '#' characters, there will be problems with the URL in
  19. * the InputSource (because a URL like
  20. * http://myhost.com/index#anchor is treated the same as
  21. * http://myhost.com/index) Thanks to Christian Oetterli
  22. */
  23. InputSource source = new InputSource(new FileInputStream(file));
  24. if (this.encoding != null) {
  25. source.setEncoding(this.encoding);
  26. }
  27. String path = file.getAbsolutePath();
  28.  
  29. if (path != null) {
  30. // Code taken from Ant FileUtils
  31. StringBuffer sb = new StringBuffer("file://");
  32.  
  33. // add an extra slash for filesystems with drive-specifiers
  34. if (!path.startsWith(File.separator)) {
  35. sb.append("/");
  36. }
  37.  
  38. path = path.replace('\\', '/');
  39. sb.append(path);
  40.  
  41. source.setSystemId(sb.toString());
  42. }
  43.  
  44. return read(source);
  45. } catch (FileNotFoundException e) {
  46. throw new DocumentException(e.getMessage(), e);
  47. }
  48. }

java.net.URL.java中抛异常的位置:

  1. /**
  2. * Creates a <code>URL</code> object from the specified
  3. * <code>protocol</code>, <code>host</code>, <code>port</code>
  4. * number, <code>file</code>, and <code>handler</code>. Specifying
  5. * a <code>port</code> number of <code>-1</code> indicates that
  6. * the URL should use the default port for the protocol. Specifying
  7. * a <code>handler</code> of <code>null</code> indicates that the URL
  8. * should use a default stream handler for the protocol, as outlined
  9. * for:
  10. * java.net.URL#URL(java.lang.String, java.lang.String, int,
  11. * java.lang.String)
  12. *
  13. * <p>If the handler is not null and there is a security manager,
  14. * the security manager's <code>checkPermission</code>
  15. * method is called with a
  16. * <code>NetPermission("specifyStreamHandler")</code> permission.
  17. * This may result in a SecurityException.
  18. *
  19. * No validation of the inputs is performed by this constructor.
  20. *
  21. * @param protocol the name of the protocol to use.
  22. * @param host the name of the host.
  23. * @param port the port number on the host.
  24. * @param file the file on the host
  25. * @param handler the stream handler for the URL.
  26. * @exception MalformedURLException if an unknown protocol is specified.
  27. * @exception SecurityException
  28. * if a security manager exists and its
  29. * <code>checkPermission</code> method doesn't allow
  30. * specifying a stream handler explicitly.
  31. * @see java.lang.System#getProperty(java.lang.String)
  32. * @see java.net.URL#setURLStreamHandlerFactory(
  33. * java.net.URLStreamHandlerFactory)
  34. * @see java.net.URLStreamHandler
  35. * @see java.net.URLStreamHandlerFactory#createURLStreamHandler(
  36. * java.lang.String)
  37. * @see SecurityManager#checkPermission
  38. * @see java.net.NetPermission
  39. */
  40. public URL(String protocol, String host, int port, String file,
  41. URLStreamHandler handler) throws MalformedURLException {
  42. if (handler != null) {
  43. SecurityManager sm = System.getSecurityManager();
  44. if (sm != null) {
  45. // check for permission to specify a handler
  46. checkSpecifyHandler(sm);
  47. }
  48. }
  49.  
  50. protocol = protocol.toLowerCase();
  51. this.protocol = protocol;
  52. if (host != null) {
  53.  
  54. /**
  55. * if host is a literal IPv6 address,
  56. * we will make it conform to RFC 2732
  57. */
  58. if (host != null && host.indexOf(':') >= 0
  59. && !host.startsWith("[")) {
  60. host = "["+host+"]";
  61. }
  62. this.host = host;
  63.  
  64. if (port < -1) {
  65. throw new MalformedURLException("Invalid port number :" +
  66. port);
  67. }
  68. this.port = port;
  69. authority = (port == -1) ? host : host + ":" + port;
  70. }
  71.  
  72. Parts parts = new Parts(file);
  73. path = parts.getPath();
  74. query = parts.getQuery();
  75.  
  76. if (query != null) {
  77. this.file = path + "?" + query;
  78. } else {
  79. this.file = path;
  80. }
  81. ref = parts.getRef();
  82.  
  83. // Note: we don't do validation of the URL here. Too risky to change
  84. // right now, but worth considering for future reference. -br
  85. if (handler == null &&
  86. (handler = getURLStreamHandler(protocol)) == null) {
  87. throw new MalformedURLException("unknown protocol: " + protocol);
  88. }
  89. this.handler = handler;
  90. }

Dom4j SAXReader Constructors的更多相关文章

  1. How to Validate XML using Java

    Configure Java APIs (SAX, DOM, dom4j, XOM) using JAXP 1.3 to validate XML Documents with DTD and Sch ...

  2. JavaWeb知识点总结

    >一: 创建Web项目项目说明:1.java Resources:java源文件2.WebContent:网页内容html.css.js.jsp.资源.配置文件等 HTML:Hyper Text ...

  3. Spring源码试读--BeanFactory模拟实现

    动机 现在Springboot越来越便捷,如果简单的Spring应用,已无需再配置xml文件,基本可以实现全注解,即使是SpringCloud的那套东西,也都可以通过yaml配置完成.最近一年一直在用 ...

  4. java解析XML saxReader.read(xml) 错误:org.dom4j.DocumentException: no protocol

    java解析XML saxReader.read(xml) 错误:org.dom4j.DocumentException: no protocol 完整错误信息: org.dom4j.Document ...

  5. Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/dom4j/io/SAXReader

    Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/dom4j/io/SAXReader ...

  6. 使用dom4j中SAXReader解析xml数据

    public ApiConfig(String configFilePath) throws DocumentException{ SAXReader reader = new SAXReader() ...

  7. XML技术之DOM4J解析器

    由于DOM技术的解析,存在很多缺陷,比如内存溢出,解析速度慢等问题,所以就出现了DOM4J解析技术,DOM4J技术的出现大大改进了DOM解析技术的缺陷. 使用DOM4J技术解析XML文件的步骤? pu ...

  8. 四种解析和创建方式(DOM,SAX,DOM4J,JDOM)

    一.先导入jar包 DOM基于树形,SAX基于事件,DOM4J和JDOM基于底层API 二.代码如下 1 package com.sxt.test; import java.io.File; impo ...

  9. dom4j的小例子

    1.要解析的xml文件book.xml <?xml version="1.0" encoding="UTF-8"?> <books> & ...

随机推荐

  1. HDU 4740 模拟题意

    九野的博客,转载请注明出处:http://blog.csdn.net/acmmmm/article/details/11711743 题意:驴和老虎在方格中跑,跑的方式:径直跑,若遇到边界或之前走过的 ...

  2. tweenanim动画

    1.视图 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:too ...

  3. uva 10330 - Power Transmission(网络流)

    uva 10330 - Power Transmission 题目大意:最大流问题. 解题思路:増广路算法. #include <stdio.h> #include <string. ...

  4. 用来解析,格式化,存储和验证国际电话号码:libphonenumber

    用来解析,格式化,存储和验证国际电话号码:libphonenumber libphonenumber是Google的公共Java.C++和Javascript库用来解析,格式化,存储和验证国际电话号码 ...

  5. centos7安装codeblocks教程

    author:lidabo 装了好多次系统,每次装的时候都有要在网上各种查,太麻烦了.所以决定记录一下,以后用到的时候会方便一些.当然,本文来源于网络,取百家之长,最重要的是本人已验证过,说明对本系统 ...

  6. PHP - 验证用户名

    /** * * 函数名:_check_username($user_str,$min_num,$max_num); * 作用:检测用户名是否符合格式 * 参数: * 1:用户名 * 2:不得小于多少位 ...

  7. SQL模板和模板实例化

    需求:需要得出一个数据源DataTable,我已知SQL和HttpRequest如何,通过SQL模板的方式去实例化匹配HttpRequest中的参数实例化为查询SQL,最后返回DataTable 1. ...

  8. 程序启动报错:ORA-12505;PL/SQL却可以登录的解决方法

    一.异常{ ORA-12505, TNS:listener does not currently know of SID given in connect descriptor The Connect ...

  9. Properties文件及与之相关的System.getProperties操作(转)

    如何使用Java读写系统属性? 读: 简述properties文件的结构和基本用法结构:扩展名为properties的文件,内容为key.value的映射,例如"a=2" 示例用到 ...

  10. VC Office2007界面对话框实现

    我们知道VS2008SP1之后,MFC就多了一个功能包,可以快速的建立一个ribbon的界面,视觉样式可以在office 2007蓝.黑等颜色之间切换,这对于单文档/多文档做界面非常方便,而且也蛮好看 ...