Java(JAXP)XML解析DocumentBuilder的差异 [英] Java (JAXP) XML parsing differences of DocumentBuilder
问题描述
-
DocumentBuilder.parse(InputStream)
和 -
DocumentBuilder.parse(InputSource)
?
我只能发现,对于第一种情况,解析器从流中检测编码,因此它更安全,而后者我不知道是否需要设置编码。
我应该注意的任何其他要点(例如性能)
p>主要区别是,第一个允许您仅从二进制源读取XML内容,基于 InputStream
界面。即:直接从文件(使用 FileInputStream
),一个打开的Socket(从 Socket.getInputStream()
)等。
第二个, DocumentBuilder.parse(InputSource)
,允许您从二进制源读取数据(这是一个 InputStream
impl)和从字符源( 阅读器
实现)。所以,使用这个你可以使用一个XML字符串(使用 StringReader
)或一个 BufferedReader
。
使用第二种方法,您已经有机会处理
InputStreams
,第一种是一种快捷方式,所以当您有一个 InputStream
您不需要创建一个新的 InputSource
。实际上, InputStream
方法的源代码是: public文件解析(InputStream is)
throws SAXException,IOException {
if(is == null){
throw new IllegalArgumentException(InputStream not not null);
}
InputSource in = new InputSource(is);
return parse(in);
}
Is there any kind of difference between
DocumentBuilder.parse(InputStream)
andDocumentBuilder.parse(InputSource)
?
I could only find that for the first case, the parser detects the encoding from the stream so it is safer while in the latter I am not sure if it is required to set the encoding.
Any other points (e.g. performance) I should be aware?
The main difference is that the first one allows you to read your XML content only from binary sources, based on the implementations of the InputStream
interface. I.e: directly from a file (using a FileInputStream
), an open Socket (from Socket.getInputStream()
), etc.
The second one, DocumentBuilder.parse(InputSource)
, allows you to read data from binary sources too (this is, an InputStream
impl) and from character sources (Reader
implementations). So, with this one you can use an XML String (using a StringReader
), or a BufferedReader
.
While with the second method you already have the chance to handle InputStreams
, the first one is a kind of shortcut, so when you have an InputStream
you don't need to create a new InputSource
. In fact, the source code of the InputStream
method is:
public Document parse(InputStream is)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource in = new InputSource(is);
return parse(in);
}
这篇关于Java(JAXP)XML解析DocumentBuilder的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!