按照SAX,默认处理文档,
public void characters(char[] ch,
int start,
int length)
throws SAXException
解析器将调用此方法来报告字符 每个数据块。 SAX解析器可能会将所有连续的字符数据返回到单个块中,或者它们可能会将其分割为多个块;但是,任何单个事件中的所有 字符都必须来自相同的外部实体 ,以便定位器提供有用的信息。
所以解析器可以调用字符的方法一次或多次的一个元素中一个特定的文字说,“不要这个周末忘了我吧!”,直到整个文本阅读。
注:
应用程序必须不尝试从数组中 指定的范围外读取。
以下代码显示了如何收集单个XML元素中的文本。
boolean isTagInScope = false;
StringBuilder elementContent = new StringBuilder();
public void startElement(String namespaceURI, String lName, String qName,
Attributes attributes) throws SAXException
{
isTagInScope = true;
}
public void endElement(String namespaceURI, String sName, String qName)
throws SAXException throws SAXException {
isTagInScope = false;
}
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
if(isTagInScope)
{
String content = new String(arg0, arg1, arg2);
elementContent.append(content);
}
}
'elementContent'变量将保存元素开始和结束标记之间的全部内容。
的DocumentBuilder分贝= DocumentBuilderFactory.newInstance()newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(xml.getBytes())); String bodyText = doc.getElementsByTagName(“body”)。item(0).getTextContent(); – DmitryKanunnikoff 2014-09-04 17:11:32
尝试使用DOM解析器。在这种情况下更容易。 – DmitryKanunnikoff 2014-09-04 17:12:37