2010-01-14 28 views
7

Teniendo en cuenta este fragmento XMLSAX análisis - manera eficaz de obtener los nodos de texto

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

en Sax, es fácil de obtener los valores de atributos:

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

Pero para obtener el valor de un nodo de texto , p.ej el valor de la etiqueta <author>, es bastante difícil ...

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. No estoy seguro de la muestra anterior es aún trabajando, ¿qué opinas de este enfoque?
  2. ¿Hay una manera mejor? (para obtener el valor del nodo de texto)
+1

es el más eficiente creo ... – nanda

Respuesta

8

Esa es la forma habitual de hacerlo con SAX.

Solo tenga en cuenta que characters() se puede llamar más de una vez por etiqueta. Consulte esto question para obtener más información. Aquí hay un completo example.

De lo contrario, podría probar StAX.

+0

gran ejemplo - gracias! – 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  ? 
     } 

    } 
Cuestiones relacionadas