在 android 應用程序中,我要解析一個 xml 頁面。xml 頁面中的數據是下面這種格式:
<root>
<tag1>data</tag1>
<tag2>
<div>data1</div><div>data2</div>
</tag2>
</root>
通過 sax 解析來獲取數據:
if (localName.equalsIgnoreCase("tag1"))
if (localName.equalsIgnoreCase("tag2"))
但是我不能從tag2中得到任何數據,能從tag1中獲得值。我想獲取所有數據包括div標簽
然後把數據顯示在html頁面上。
使用下面的代碼,應該能達到你要的功能。
currentTag = localName;
if ("tag1".equalsIgnoreCase(localName)) {
responseTag = new StringBuffer();
}else if ("tag2".equalsIgnoreCase(localName)) {
responseTag = new StringBuffer();
}else if ("div".equalsIgnoreCase(localName)) {
responseTag = new StringBuffer();
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
String responseValue = responseTag.toString().trim();
if ("tag1".equalsIgnoreCase(localName)) {
Log.v("TAG", "Tag 1 value "+responseValue);
}else if ("tag2".equalsIgnoreCase(localName)) {
Log.v("TAG", "Tag 2 value "+responseValue);
}else if ("div".equalsIgnoreCase(localName)) {
Log.v("TAG", "div value "+responseValue);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
str = new String(ch, start, length);
if ("tag1".equalsIgnoreCase(currentTag)) {
responseTag.append(str);
}else if ("tag2".equalsIgnoreCase(currentTag)) {
responseTag.append(str);
}else if ("div".equalsIgnoreCase(currentTag)) {
responseTag.append(str);
}
}
}