Donné le XML extraitanalyse syntaxique SAX - moyen efficace pour obtenir les nœuds texte
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
En SAX, il est facile d'obtenir des valeurs d'attribut:
@Override
public void startElement (String uri, String localName,
String qName, Attributes attributes) throws SAXException{
if(qName.equals("book")){
String bookId = attributes.getValue("id");
...
}
}
Mais pour obtenir la valeur d'un nœud de texte , par exemple la valeur de la balise <author>
, il est assez difficile ...
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();
}
}
- Je ne suis pas sûr que l'exemple ci-dessus travaille même, que pensez-vous de cette approche?
- Y a-t-il un meilleur moyen? (pour obtenir la valeur du nœud de texte)
c'est le plus efficace je pense ... – nanda