Java(JAXP)DocumentBuilder的XML解析差异
之间有什么区别吗
DocumentBuilder.parse(InputStream)
和DocumentBuilder.parse(InputSource)
?我只能发现,对于第一种情况,解析器从流中检测编码,因此更安全,而在后者中我不确定是否需要设置编码。
我还应该注意其他几点(例如性能)吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
主要区别在于,第一个允许您仅从二进制源读取 XML 内容,基于
InputStream
接口。即:直接从文件(使用FileInputStream
),一个打开的套接字(来自Socket.getInputStream()
) 等第二个,
DocumentBuilder.parse(InputSource)
,也允许您从二进制源(这是一个InputStream
impl)读取数据和从字符源(Reader
实现)。因此,通过这个,您可以使用 XML 字符串(使用StringReader
),或BufferedReader
。虽然使用第二种方法您已经有机会处理
InputStreams
,但第一种方法是一种快捷方式,因此当您有InputStream
时,您不需要创建一个新的InputSource
。事实上,InputStream
方法的源码是: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 aFileInputStream
), an open Socket (fromSocket.getInputStream()
), etc.The second one,
DocumentBuilder.parse(InputSource)
, allows you to read data from binary sources too (this is, anInputStream
impl) and from character sources (Reader
implementations). So, with this one you can use an XML String (using aStringReader
), or aBufferedReader
.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 anInputStream
you don't need to create a newInputSource
. In fact, the source code of theInputStream
method is: