给定这个 XML 片段
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
在SAX中,获取属性值很容易:
@Override
public void startElement (String uri, String localName,
String qName, Attributes attributes) throws SAXException{
if(qName.equals("book")){
String bookId = attributes.getValue("id");
...
}
}
但要获取文本节点的值,例如<author>
的值tag,挺难的……
private StringBuffer curCharValue = new StringBuffer(1024);
@Override
public void startElement (String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if(qName.equals("author")){
curCharValue.clear();
}
}
@Override
public void characters (char ch[], int start, int length) throws SAXException
{
//already synchronized
curCharValue.append(char, start, length);
}
@Override
public void endElement (String uri, String localName, String qName)
throws SAXException
{
if(qName.equals("author")){
String author = curCharValue.toString();
}
}
- 我不确定上述示例是否有效,您如何看待这种方法?
- 有更好的方法吗? (获取文本节点的值)
最佳答案
关于java - SAX 解析——获取文本节点的高效方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2064679/