Java(JAXP)XML解析DocumentBuilder的差异 [英] Java (JAXP) XML parsing differences of DocumentBuilder

查看:99
本文介绍了Java(JAXP)XML解析DocumentBuilder的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. DocumentBuilder.parse(InputStream)

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

  1. DocumentBuilder.parse(InputStream) and
  2. DocumentBuilder.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆