SAX只获取内容字符串的结尾

时间:2013-09-16 17:27:44

标签: xml-parsing sax podcast

我需要从< itunes:sumary>标签,但我的处理程序只获得标签内容的结尾(例如最后三个单词)。我不知道该怎么办,因为正在按预期处理其他标签,获取所有内容。*

我已经看到解析器忽略了一些标签,但我不认为它正在发生,因为正如我所说它获取内容但只是结束。

源XML托管在 - > http://djpaulonla.podomatic.com/archive/rss2.xml

拜托,有人可以帮帮我吗??? 代码如下:

public class PodOMaticCustomHandler extends CustomHandler {

public PodOMaticCustomHandler(int quantityToFetch, String startTagValue,
        String endTagValue) {
    super(quantityToFetch, startTagValue, endTagValue);
}

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
    super.characters(ch, start, length);
    this.value = new String(ch, start, length);
}

@Override
public void endDocument() throws SAXException {
    super.endDocument();
    this.endDoc = true;
}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    super.endElement(uri, localName, qName);

    if (this.podcast != null) {
        if (qName.equalsIgnoreCase("title")) {
            podcast.setTitle(this.value);
        } else if (qName.equalsIgnoreCase("pubDate")) {
            podcast.setPubDate(this.value);
        } else if (qName.equalsIgnoreCase("description")) {
            podcast.setContent(this.value);
        } else if (qName.equalsIgnoreCase("guid")) {
            this.podcast.setLink(value);
        }
    }

}

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
    super.startElement(uri, localName, qName, attributes);

    if (this.startTagValue == null) {
        this.startTagValueFound = true;
    } else if (qName.equalsIgnoreCase("guid")
            && this.value.equalsIgnoreCase(this.startTagValue)) {
        this.startTagValueFound = true;
    }
    if (this.endTagValue != null) {
        if (qName.equalsIgnoreCase("guid")
                && this.value.equalsIgnoreCase(this.endTagValue)) {
            this.endDoc = true;
        }
    }
    if (!this.endDoc) {
        if (this.quantityToFetch != this.podcasts.size()) {
            if (this.startTagValueFound == true) {
                if (qName.equalsIgnoreCase("item")) {
                    this.podcast = new Podcast();
                } else if (qName.equalsIgnoreCase("enclosure")) {
                    this.podcast.setMedia(attributes.getValue("url"));
                    this.podcasts.add(podcast);
                }
            }
        } else {
            this.podcast = null;
        }
    }else{
        this.podcast = null;
      }
    }
  }

1 个答案:

答案 0 :(得分:1)

您不能依赖于使用整个元素文本调用一次的字符方法,它可能会被多次调用,每次只有部分文本。

向字符方法添加一个调试日志语句,显示你设置的值,然后你会看到这些值是用字符串的第一部分设置的,然后被最后一部分覆盖。

答案是缓冲从CharArrayWriter或StringBuilder中的字符调用传入的文本。然后,当找到元素的末尾时,你必须清除缓冲区。

以下是the Java tutorial on SAX关于字符方法的内容:

  

解析器不需要一次返回任何特定数量的字符。解析器可以一次从单个字符返回任何内容,但仍然是符合标准的实现。因此,如果您的应用程序需要处理它看到的字符,那么使用characters()方法在java.lang.StringBuffer中累积字符并且只有在您确定已找到所有字符时才对它们进行操作是明智的。 / p>