Pregunta

Estoy usando analizador SAX en mi aplicación Android para leer algunos alimentos a la vez. La secuencia de comandos se ejecuta como sigue.

                     // Begin FeedLezer
                    try {

                        /** Handling XML **/
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();
                        XMLReader xr = sp.getXMLReader();

                        /** Send URL to parse XML Tags **/
                        URL sourceUrl = new URL(
                            BronFeeds[i]);

                        /** Create handler to handle XML Tags ( extends DefaultHandler ) **/
                        Feed_XMLHandler myXMLHandler = new Feed_XMLHandler();
                        xr.setContentHandler(myXMLHandler);
                        xr.parse(new InputSource(sourceUrl.openStream()));

                    } catch (Exception e) {
                        System.out.println("XML Pasing Excpetion = " + e);
                    }
                     sitesList = Feed_XMLHandler.sitesList;

                    String titels = sitesList.getMergedTitles();

Y aquí están Feed_XMLHandler.java y Feed_XMLList.java , que básicamente tanto acaba de tomar de la web.

Sin embargo, este código falla a veces. Voy a mostrar algunos ejemplos.

http://imm.io/media/2I/2IAs.jpg Va muy bien aquí. Incluso reconoce y muestra apóstrofes. Incluso cuando los artículos se abren al hacer clic, casi todos los espectáculos de texto, por lo que todo está bien. La alimentación de la fuente está aquí. No puedo controlar la alimentación.

http://imm.io/media/2I/2IB1.jpg Aquí , no va tan bien. Lo hace visualizar el yo, sino que se ahoga con el apóstrofe (no se supone que es 'NORAD' después de la Waarom). Aquí

http://imm.io/media/2I/2IBQ.jpg Este es el peor. Como se puede ver, el título sólo muestra un apóstrofe, mientras que se supone que es un 'blablabla'. Además, los extremos de texto en el centro de la línea, sin ningún carácter especial en la cita. La alimentación es aquí

En todos los casos, no tengo ningún control sobre la alimentación. Creo que el guión no ahogarse con caracteres especiales. ¿Cómo puedo estar seguro de SAX obtiene todas las cuerdas correctamente?

Si alguien sabe la respuesta a esto, realmente me ayudará mucho: D

Gracias de antemano.

¿Fue útil?

Solución

This is from the FAQ of Xerces.

Why does the SAX parser lose some character data or why is the data split into several chunks? If you read the SAX documentation, you will find that SAX may deliver contiguous text as multiple calls to characters, for reasons having to do with parser efficiency and input buffering. It is the programmer's responsibility to deal with that appropriately, e.g. by accumulating text until the next non-characters event.

You're code is very well adapted from one of many XML Parsing tutorials (like this one here) Now, the tutorial is good and all, but they fail to mention something very important...

Notice this part here...

    public void characters(char[] ch, int start, int length)
            throws SAXException
    {
              if(in_ThisTag){
                     myobj.setName(new String(ch,start,length))
              }
    }

I bet at this point you're checking up booleans to mark which tag you're under and then setting a value in some kind of class you made? or something like that....

But the problem is, the SAX parser (which is buffered) will not necesarily get you all the characters between a tag at one go....say if <tag> Lorem Ipsum...really long sentence...</tag> so your SAX parser calls characters function is chunks....

So the trick here, is to keep appending the values to a string variable and the actually set (or commit) it to your structure when the tag ends...(ie in endElement)

Example

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {

    currentElement = false;

    /** set value */
    if (localName.equalsIgnoreCase("tag"))
            {
        sitesList.setName(currentValue);
                    currentValue = ""; //reset the currentValue
            }

}

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {

    if (in_Tag) {
        currentValue += new String(ch, start, length); //keep appending string, don't set it right here....maybe there's more to come.
    }

}

Also, it would be better if you use StringBuilder for the appending, since that'll be more efficient....

Hope it makes sense! If it didn't check this and here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top