2010-01-14 7 views
7

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(); 
    } 
} 
  1. Je ne suis pas sûr que l'exemple ci-dessus travaille même, que pensez-vous de cette approche?
  2. Y a-t-il un meilleur moyen? (pour obtenir la valeur du nœud de texte)
+1

c'est le plus efficace je pense ... – nanda

Répondre

8

C'est la manière habituelle de le faire avec SAX. Il suffit de se méfier que characters() peut être appelé plus d'une fois par étiquette.

Voir ce question pour plus d'informations. Voici un complet example.

Sinon, vous pouvez essayer StAX.

+0

grand exemple - merci !!! – jsh

1
public void startElement(String strNamespaceURI, String strLocalName, 
     String strQName, Attributes al) throws SAXException { 
     if(strLocalName.equalsIgnoreCase("HIT")) 
     { 
      String output1 = al.getValue("NAME"); 
      //this will work but how can we parse if NAME="abc" only  ? 
     } 

    }