0

我有一个正在解析的 xml,其中有一个包含很长文本的字段,但不知何故它被解析器删除了,是不是因为我只使用字符串来获取那些字符,如果我使用字符串缓冲区或构建器。我想要的是仅按标签提取值。

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

    if (elementOn) {
     // its not reading element value, though tag is read.
        elementValue = new String(ch, start, length);
        elementOn = false;
    }
}

这是文本:

  <description>
   <![CDATA[
  Former CPI MLA Manish Kunjam, who returned on Thursday after, theis is a long long text very long that its being dropped.......so what can be done...................................................................................................
  ]]>
 </description>

谢谢请指导我.....

4

1 回答 1

2

是的,使用 StringBuilder 因为可以分块读取文本,并且您可能正在读取像这样的第一行空代码。查看文档

您可以在每次点击时重置 StringBuilderstartElement

private final StringBuilder mStringBuilder = new StringBuilder();
private String elementValue = null;
private boolean elementOn = false;

public final void characters(char[] ch, int start, int length) throws SAXException {
     if (elementOn)
         mStringBuilder.append(ch, start, length);
}

public final void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    mStringBuilder.setLength(0);
    if (someCondition) elementOn = true;
}

public void endElement(String uri, String localName, String qName) throws SAXException {
     elementValue = mStringBuilder.toString().trim();
     elementOn = false;
}

解析器执行以下操作

  <description> -> startElement("description"), reset StringBuilder
   <![CDATA[    -> characters(""), appended to (empty) String 
  Former CPI..  -> characters("Former.."), appended 
  ]]>           -> characters(""), appended
 </description> -> endElement("description"), read text here
 <description> -> startElement("description"), reset StringBuilder all starts again
于 2012-04-26T12:04:42.507 回答