我正在尝试解析一个这样构建的XML页面:http://pastebin.com/t9cXdnGs。 我按照本教程Anddev SAX tutorial实现了一个基本的SAX解析器。
它工作得很好,除了我只得到最后一个标签的值。为了解决这个问题,我实现了一个ArrayList来添加每个XML节点生成的每个对象。但是现在我得到了一些奇怪的输出。对于他在循环中传递的每个节点,他再次添加相同的值。所以对于节点1,我得到一次值,对于节点2,我得到两次值,依此类推......(例如:value1,value2value2,value3value3value3)
我似乎无法弄清楚出了什么问题......
以下是该页面的完整源代码:http://pastebin.com/bkyz0g1U
答案 0 :(得分:0)
您一遍又一遍地重复使用同一个对象,因此您只需在ArrayList
中添加一个对象。替换此行:
private Vacature vacature = new Vacature();
与
private Vacature vacature;
并添加以下行:
vacature = new Vacature();
在您声明characters()
方法之后:
public void characters(char ch[], int start, int length) {
我还怀疑getVacatures()
应该返回ArrayList
arrayVaca
。
答案 1 :(得分:0)
我很快将代码更改为更简单的解决方案:
package stage.accent.webservice;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import stage.accent.domain.Vacature;
public class vacatureWebservice extends DefaultHandler {
private ArrayList<Vacature>arrayVaca = new ArrayList<Vacature>();
private Vacature vacature = null;
public ArrayList<Vacature> getVacatures() {
return this.arrayVaca;
}
public StringBuilder buff = new StringBuilder();
@Override
public void startDocument() throws SAXException {
this.vacature = new Vacature();
}
@Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
}
/** Gets be called on closing tags like:
* </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("vacatures")) {
}else if (localName.equals("vacature")) {
}else if (localName.equals("titel")) {
vacature.setTitel(buff.toString());
}else if (localName.equals("werkveld")){
vacature.setWerkveld(buff.toString());
}else if (localName.equals("regio")){
vacature.setRegio(buff.toString());
arrayVaca.add(vacature);
vacature = new Vacature();
}
buff = new StringBuilder();
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {
if (buff!=null) {
for (int i=start; i<start+length; i++) {
buff.append(ch[i]);
}
}
}
}