yan*_*isf 9 java xml sax xml-parsing
在Java中使用SAX api解析一个没有来自流输入的根元素的XML片段列表是否可行?
我尝试解析这样的XML,但得到了一个
org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
Run Code Online (Sandbox Code Playgroud)
甚至在endDocument事件被触发之前.
我不想解决明显但笨拙的解决方案,如"预先添加自定义根元素或使用缓冲片段解析".
我使用的是Java 1.6的标准SAX API.如果有人想知道,SAX工厂已经设置了错误(假).
npe*_*npe 13
首先,最重要的是,您要解析的内容不是XML文档.从XML规范:
[定义:只有一个元素,称为根或文档元素,其中任何部分都不会出现在任何其他元素的内容中.
现在,至于用SAX解析这个 - 尽管你说的是笨拙 - 我建议采用以下方法:
Enumeration<InputStream> streams = Collections.enumeration(
Arrays.asList(new InputStream[] {
new ByteArrayInputStream("<root>".getBytes()),
yourXmlLikeStream,
new ByteArrayInputStream("</root>".getBytes()),
}));
SequenceInputStream seqStream = new SequenceInputStream(streams);
// Now pass the `seqStream` into the SAX parser.
Run Code Online (Sandbox Code Playgroud)
使用the SequenceInputStream是将多个输入流连接成单个流的便捷方式.它们将按照传递给构造函数的顺序读取(或者在本例中由 - 返回Enumeration).
将它传递给你的SAX解析器,你就完成了.