SAX parsing of '&' character [duplicate]

2020-04-21 05:03发布

问题:

I am facing a problem in SAX parsing when I am trying to parse & char, All the other special chars are parsed automatically in SAX parser,but I am facing problem in & character.. anyone pls suggest me something??

Firstly I am saving my XML coming from webservices into a string and checking it side by side as

     if(ques_xml.contains("&"))
     {
                ques_xml=ques_xml.replaceAll("&", "&");
    }

//And the following method I am using to parse my saved XML. public void XmlParsing(String questions_xml) { try {

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

        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        MyXmlHandler myXMLHandler = new MyXmlHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse( new InputSource(new StringReader(questions_xml)));


        } catch (Exception e) {
            String err = (e.getMessage()==null)?"XMLParsing exception":e.getMessage();
            Log.e("XMLParsing Exception",err); 
        }


}

回答1:

There are always problem in special symbol (&) parsing using SAX parser, I think this only thing can help you, Handling Special Characters

EDIT:

When you are handling large blocks of XML or HTML that include many special characters, you can use a CDATA section. A CDATA section works like <code>...</code> in HTML, only more so: all white space in a CDATA section is significant, and characters in it are not interpreted as XML. A CDATA section starts with .



回答2:

In this case you can use StringBuffer.

Initialize the StringBuffer in the startElement.

   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //reset
         buffer = new StringBuffer();
....
}

Then in the characters just add the content to the StringBuffer.

public void characters(char[] ch, int start, int length) throws SAXException {
        buffer.append(new String(ch,start,length));
    }

And then finally use this StringBuffer in the endElement.

public void endElement(String uri, String localName, String qName) throws SAXException {
       // use StringBuffer's object buffer here
}

This will surely work.