Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse an xml string in java?

Tags:

java

xml

how do you parse xml stored in a java string object?

Java's XMLReader only parses XML documents from a URI or inputstream. is it not possible to parse from a String containing an xml data?

Right now I have the following:

try {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser sp = factory.newSAXParser();
    XMLReader xr = sp.getXMLReader(); 

    ContactListXmlHandler handler = new ContactListXmlHandler();
    xr.setContentHandler(handler);
    xr.p
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

And on my handler i have this:

public class ContactListXmlHandler extends DefaultHandler implements Resources {

    private List<ContactName> contactNameList = new ArrayList<ContactName>();

    private ContactName contactItem;

    private StringBuffer sb;

    public List<ContactName> getContactNameList() {
        return contactNameList;
    }

    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.startDocument();

        sb = new StringBuffer();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        super.startElement(uri, localName, qName, attributes);
        if(localName.equals(XML_CONTACT_NAME)){
            contactItem = new ContactName();
        }

        sb.setLength(0);

    }

    @Override
    public void characters(char[] ch, int start, int length){
        // TODO Auto-generated method stub
        try {
            super.characters(ch, start, length);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sb.append(ch, start, length);
    }

    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
    }

    /**
     * where the real stuff happens
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        //super.endElement(arg0, arg1, arg2);

        if(contactItem != null){
            if (localName.equalsIgnoreCase("title")) {
                contactItem.setUid(sb.toString());
                Log.d("handler", "setTitle = " + sb.toString());

            } else if (localName.equalsIgnoreCase("link")) {
                contactItem.setFullName(sb.toString());

            } else if (localName.equalsIgnoreCase("item")){
                Log.d("handler", "adding rss item");
                contactNameList.add(contactItem);
            }

            sb.setLength(0);
        }
}

Thanks in advance

like image 727
Jonathan Avatar asked Oct 11 '10 13:10

Jonathan


3 Answers

The SAXParser can read an InputSource.

An InputSource can take a Reader in its constructor

So, you can put parse XML string via a StringReader

new InputSource(new StringReader("... your xml here....")));
like image 75
Pierre Avatar answered Nov 15 '22 14:11

Pierre


Try jcabi-xml (see this blog post) with a one-liner:

XML xml = new XMLDocument("<document>...</document>")
like image 21
yegor256 Avatar answered Nov 15 '22 14:11

yegor256


Your XML might be simple enough to parse manually using the DOM or SAX API, but I'd still suggest using an XML serialization API such as JAXB, XStream, or Simple instead because writing your own XML serialization/deserialization code is a drag.

Note that the XStream FAQ erroneously claims that you must use generated classes with JAXB:

How does XStream compare to JAXB (Java API for XML Binding)?

JAXB is a Java binding tool. It generates Java code from a schema and you are able to transform from those classes into XML matching the processed schema and back. Note, that you cannot use your own objects, you have to use what is generated.

It seems this was true was true at one time, but JAXB 2.0 no longer requires you to use Java classes generated from a schema.

If you go this route, be sure to check out the side-by-side comparisons of the serialization/marshalling APIs I've mentioned:

http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-simple.html

like image 27
rob Avatar answered Nov 15 '22 13:11

rob