【发布时间】:2011-01-05 02:24:31
【问题描述】:
鉴于此 XML sn-p
<?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>标签的值,挺难的……
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();
}
}
- 我不确定上述示例是否有效,您如何看待这种方法?
- 有没有更好的方法? (获取文本节点的值)
【问题讨论】:
-
这是我认为效率最高的...