2010-01-14 14 views
7

Dato questo frammento XMLSAX parsing - modo efficiente per ottenere i nodi di testo

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
     <author>Gambardella, Matthew</author> 

In SAX, è facile da ottenere valori degli attributi:

@Override 
public void startElement (String uri, String localName, 
       String qName, Attributes attributes) throws SAXException{ 
    if(qName.equals("book")){ 
     String bookId = attributes.getValue("id"); 
     ... 
    } 
} 

Ma per ottenere il valore di un nodo di testo , per esempio il valore del tag <author>, è abbastanza 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. Non sono sicuro che il campione di cui sopra è ancora lavorando, cosa ne pensate di questo approccio?
  2. C'è un modo migliore? (per ottenere il valore del nodo di testo)
+1

è il più efficiente penso ... – nanda

risposta

8

Questo è il solito modo di farlo con SAX.

Basta fare attenzione che characters() può essere chiamato più di una volta per tag. Vedi questo question per maggiori informazioni. Ecco un completo example.

Altrimenti si potrebbe provare a StAX.

+0

ottimo esempio - grazie !!! – 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  ? 
     } 

    } 
Problemi correlati