Dom4j读取xml:
eg1:

package xml;

import java.io.File;

import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader; public class XmlReader_Dom4j {
public static void main(String[] args) {
String path = "D:\\test\\中文文件夹名\\namespaces.xml";
readXml(path);//will throw exception
File xmlFile=new File(path);
readXml(xmlFile);
path = "D:\\test\\path withWhiteSpace\\namespaces.xml";
readXml(path); path = "D:\\test\\normal\\namespaces.xml";
readXml(path);
} private static void readXml(String path) {
SAXReader saxReader=new SAXReader();
try {
saxReader.read(path);
System.out.println("success");
} catch (DocumentException e) {
e.printStackTrace();
}
} private static void readXml(File xmlFile) {
SAXReader saxReader=new SAXReader();
try {
saxReader.read(xmlFile);
System.out.println("success");
} catch (DocumentException e) {
e.printStackTrace();
}
} }

Output:

org.dom4j.DocumentException: unknown protocol: d Nested exception: unknown protocol: d
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.dom4j.io.SAXReader.read(SAXReader.java:321)
at xml.XmlReader_Dom4j.readXml(XmlReader_Dom4j.java:24)
at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:11)
Nested exception:
java.net.MalformedURLException: unknown protocol: d
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.dom4j.io.SAXReader.read(SAXReader.java:321)
at xml.XmlReader_Dom4j.readXml(XmlReader_Dom4j.java:24)
at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:11)
Nested exception: java.net.MalformedURLException: unknown protocol: d
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.dom4j.io.SAXReader.read(SAXReader.java:321)
at xml.XmlReader_Dom4j.readXml(XmlReader_Dom4j.java:24)
at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:11)
success
success
success

Source code:

    /**
* <p>
* Reads a Document from the given URL or filename using SAX.
* </p>
*
* <p>
* If the systemId contains a <code>':'</code> character then it is
* assumed to be a URL otherwise its assumed to be a file name. If you want
* finer grained control over this mechansim then please explicitly pass in
* either a {@link URL}or a {@link File}instance instead of a {@link
* String} to denote the source of the document.
* </p>
*
* @param systemId
* is a URL for a document or a file name.
*
* @return the newly created Document instance
*
* @throws DocumentException
* if an error occurs during parsing.
*/
public Document read(String systemId) throws DocumentException {
InputSource source = new InputSource(systemId);
if (this.encoding != null) {
source.setEncoding(this.encoding);
} return read(source);
}

eg2:

    private static void testWithUrl() throws MalformedURLException {
System.out.println("=============testWithUrlBegin============="); String path = "file:///D:\\test\\中文文件夹名\\namespaces.xml";
newUrl(path);
readXml(path); path = "D:\\test\\中文文件夹名\\namespaces.xml";
newUrl(path); System.out.println("=============testWithUrlEnd=============");
} private static void newUrl(String path) throws MalformedURLException {
try {
new URL(path);
} catch (Exception e) {
e.printStackTrace();
}
} private static void readXml(String path) {
SAXReader saxReader=new SAXReader();
try {
Document document=saxReader.read(path);
System.out.println("document.hasContent():"+document.hasContent());
System.out.println("success");
} catch (DocumentException e) {
e.printStackTrace();
}
}

Output:

=============testWithUrlBegin=============
document.hasContent():true
success
java.net.MalformedURLException: unknown protocol: d
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at xml.XmlReader_Dom4j.newUrl(XmlReader_Dom4j.java:50)
at xml.XmlReader_Dom4j.testWithUrl(XmlReader_Dom4j.java:43)
at xml.XmlReader_Dom4j.main(XmlReader_Dom4j.java:13)
=============testWithUrlEnd=============

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

    /**
* <p>
* Reads a Document from the given <code>File</code>
* </p>
*
* @param file
* is the <code>File</code> to read from.
*
* @return the newly created Document instance
*
* @throws DocumentException
* if an error occurs during parsing.
*/
public Document read(File file) throws DocumentException {
try {
/*
* We cannot convert the file to an URL because if the filename
* contains '#' characters, there will be problems with the URL in
* the InputSource (because a URL like
* http://myhost.com/index#anchor is treated the same as
* http://myhost.com/index) Thanks to Christian Oetterli
*/
InputSource source = new InputSource(new FileInputStream(file));
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
String path = file.getAbsolutePath(); if (path != null) {
// Code taken from Ant FileUtils
StringBuffer sb = new StringBuffer("file://"); // add an extra slash for filesystems with drive-specifiers
if (!path.startsWith(File.separator)) {
sb.append("/");
} path = path.replace('\\', '/');
sb.append(path); source.setSystemId(sb.toString());
} return read(source);
} catch (FileNotFoundException e) {
throw new DocumentException(e.getMessage(), e);
}
}

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

    /**
* Creates a <code>URL</code> object from the specified
* <code>protocol</code>, <code>host</code>, <code>port</code>
* number, <code>file</code>, and <code>handler</code>. Specifying
* a <code>port</code> number of <code>-1</code> indicates that
* the URL should use the default port for the protocol. Specifying
* a <code>handler</code> of <code>null</code> indicates that the URL
* should use a default stream handler for the protocol, as outlined
* for:
* java.net.URL#URL(java.lang.String, java.lang.String, int,
* java.lang.String)
*
* <p>If the handler is not null and there is a security manager,
* the security manager's <code>checkPermission</code>
* method is called with a
* <code>NetPermission("specifyStreamHandler")</code> permission.
* This may result in a SecurityException.
*
* No validation of the inputs is performed by this constructor.
*
* @param protocol the name of the protocol to use.
* @param host the name of the host.
* @param port the port number on the host.
* @param file the file on the host
* @param handler the stream handler for the URL.
* @exception MalformedURLException if an unknown protocol is specified.
* @exception SecurityException
* if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* specifying a stream handler explicitly.
* @see java.lang.System#getProperty(java.lang.String)
* @see java.net.URL#setURLStreamHandlerFactory(
* java.net.URLStreamHandlerFactory)
* @see java.net.URLStreamHandler
* @see java.net.URLStreamHandlerFactory#createURLStreamHandler(
* java.lang.String)
* @see SecurityManager#checkPermission
* @see java.net.NetPermission
*/
public URL(String protocol, String host, int port, String file,
URLStreamHandler handler) throws MalformedURLException {
if (handler != null) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// check for permission to specify a handler
checkSpecifyHandler(sm);
}
} protocol = protocol.toLowerCase();
this.protocol = protocol;
if (host != null) { /**
* if host is a literal IPv6 address,
* we will make it conform to RFC 2732
*/
if (host != null && host.indexOf(':') >= 0
&& !host.startsWith("[")) {
host = "["+host+"]";
}
this.host = host; if (port < -1) {
throw new MalformedURLException("Invalid port number :" +
port);
}
this.port = port;
authority = (port == -1) ? host : host + ":" + port;
} Parts parts = new Parts(file);
path = parts.getPath();
query = parts.getQuery(); if (query != null) {
this.file = path + "?" + query;
} else {
this.file = path;
}
ref = parts.getRef(); // Note: we don't do validation of the URL here. Too risky to change
// right now, but worth considering for future reference. -br
if (handler == null &&
(handler = getURLStreamHandler(protocol)) == null) {
throw new MalformedURLException("unknown protocol: " + protocol);
}
this.handler = handler;
}

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. StrPos,StrScan,

    Delphi提供的字符串函数里有一个Pos函数,它的定义是: function Pos(Substr: string; S: string): Integer; 它的作用是在字符串S中查找字符串Sub ...

  2. Qt 内存管理机制

    这篇文章首先发布于我的主页 http://www.devbean.info,以后也会直接发布在那里.现在有 Flex 4 的一篇和 <从 C++ 到 Objective-C>系列,感谢大家 ...

  3. Qt新建线程的方法(有QRunnable,QThreadPool,moveToThread和QtConcurrent的例子)

    看了不少Qt线程的东西,下面总结一下Qt新建一个线程的方法. 一.继承QThread 继承QThread,这应该是最常用的方法了.我们可以通过重写虚函数void QThread::run ()实现我们 ...

  4. Python 文本解析器

    Python 文本解析器 一.课程介绍 本课程讲解一个使用 Python 来解析纯文本生成一个 HTML 页面的小程序. 二.相关技术 Python:一种面向对象.解释型计算机程序设计语言,用它可以做 ...

  5. 主题:Java WebService 简单实例

    链接地址:主题:Java WebService 简单实例    http://www.iteye.com/topic/1135747 前言:朋友们开始以下教程前,请先看第五大点的注意事项,以避免不必要 ...

  6. D16Pascal的编译器和IDE

    https://github.com/Memnarch/D16Pascal https://github.com/Memnarch/D16IDE https://github.com/Memnarch ...

  7. protected的一些功能

    java的访问限制有private.protected.public.这里只想进一步认识一下protected. 我对protected有4个疑问: 1,在相同包中,是否可以调用其它类的protect ...

  8. MIPI CSI-2规范一——概述及层级

    MIPI CSI-2规范一——概述及层级 CSI-2概述 CSI-2规范定义了发送者和接收者之间传输和控制接口的标准数据.数据传输接口(指CSI-2)是单向差分串行接口,传输数据和始终信号:接口的物理 ...

  9. Android KeyCode(官方)

    Constants public static final int ACTION_DOWN Added in API level 1 getAction() value: the key has be ...

  10. 讲解下for循环的用法,加深记忆

    引子 这是一段很简单的代码,但是即便是这么简单的东西,这里我们还是需要说一下. 关于for循环整个执行流程就是,先执行var i=10,然后到了第二个语句,判断10是否大于0,很明显为true,所以此 ...