SAX parsing - efektywny sposób na uzyskanie węzłów tekstowych
Biorąc pod uwagę ten fragment kodu XML
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
W SAX łatwo jest uzyskać wartości atrybutów:
@Override
public void startElement (String uri, String localName,
String qName, Attributes attributes) throws SAXException{
if(qName.equals("book")){
String bookId = attributes.getValue("id");
...
}
}
Ale aby uzyskać wartość węzła tekstowego, np. wartość<author>
tag, to dość trudne ...
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();
}
}
Nie jestem pewien, czy powyższa próbka działa, co sądzisz o tym podejściu?Czy jest lepszy sposób? (aby uzyskać wartość węzła tekstowego)