本文介紹了SAX 解析和特殊字符的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我想使用 SAX 解析器從 xml 文件中解析一些數(shù)據(jù).我的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>
為了解析這些數(shù)據(jù),我擴(kuò)展了 DefaultHandler.
In order to parse this data I extend DefaultHandler.
解析后的輸出為:
cat 1 = Pies
cat 2 = &
cat 3 = past
cat 4 = Fruits
為什么會(huì)發(fā)生這種情況而不是得到:
Why is this happening instead of getting:
cat 1 = Pies & past
cat 2 = Fruits
推薦答案
我的猜測是,您將對 characters
的每次調(diào)用都視為為 cat
提供完整的文本元素.您應(yīng)該對處理程序進(jìn)行編碼,以便對 characters
的連續(xù)調(diào)用累積文本,并且僅在 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);
}
這篇關(guān)于SAX 解析和特殊字符的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!