What libraries are there for processing XML on Google App Engine/Java Servlet

后端 未结 8 1223
梦谈多话
梦谈多话 2021-01-18 14:23

I\'m writing a Java servlet in Eclipse (to be hosted on Google App Engine) and need to process an XML document. What libraries are available that are easy to add to an Eclip

8条回答
  •  醉酒成梦
    2021-01-18 14:57

    I ended up using JAXP with the SAX API.

    Adding something like the following to my servlet:

    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import javax.xml.parsers.*;
    
    ....
    
    InputStream in = connection.getInputStream();
    
    InputSource responseXML = new InputSource(in);
    final StringBuilder response = new StringBuilder();
    DefaultHandler myHandler = new DefaultHandler() {
    
        public void startElement(String uri, String localName, String qName, 
                Attributes attributes) throws SAXException {
            if (localName.equals("elementname")) {
                response.append(attributes.getValue("attributename"));
                inElement = true;
            }
        }
        public void characters(char [] buf, int offset, int len) {
            if (inElement) {
                inElement = false;
                String s = new String(buf, offset, len);
                response.append(s);
                response.append("\n");
            }
        }
    };
    
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(responseXML, myHandler);
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    in.close();
    connection.disconnect();
    
    ....
    

提交回复
热议问题