SAX parsing and special characters(SAX 解析和特殊字符)
问题描述
我想使用 SAX 解析器从 xml 文件中解析一些数据.我的xml如下:
I want to parse some data from an xml file using SAX parser. My xml is as follows:
<categories>
<cat>Pies & past</cat>
<cat>Fruits</cat>
</categories>
为了解析这些数据,我扩展了 DefaultHandler.
In order to parse this data I extend DefaultHandler.
解析后的输出为:
cat 1 = Pies
cat 2 = &
cat 3 = past
cat 4 = Fruits
为什么会发生这种情况而不是得到:
Why is this happening instead of getting:
cat 1 = Pies & past
cat 2 = Fruits
推荐答案
我的猜测是,您将对 characters
的每次调用都视为为 cat
提供完整的文本元素.您应该对处理程序进行编码,以便对 characters
的连续调用累积文本,并且仅在 endElement
事件中捕获它:
My guess is that you are treating each call to characters
as delivering the complete text for a cat
element. You should code your handler so that successive calls to characters
accumulate the text, and you only capture it on the endElement
event:
public class CatHandler extends DefaultHandler {
private StringBuilder chars = new StringBuilder();
public void startElement(String uri, String lName, String qName, Attributes a)
{
final String name = qName == null ? lName : qName;
if ("cat".equals(name)) {
chars.setLength(0);
} else . . .
}
public void endElement(String uri, String lName, String qName) {
final String name = qName == null ? lName : qName;
if ("cat".equals(name)) {
String catName = chars.toString();
// do something with cat name
} else . . .
}
public void characters(char[] ch, int start, int length) {
chars.append(ch, start, length);
}
这篇关于SAX 解析和特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SAX 解析和特殊字符


基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01