Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAX: How to get the content of an element

Tags:

java

xml

sax

I have some trouble understanding parsing XML structures with SAX. Let's say there is the following XML:

<root>
  <element1>Value1</element1>
  <element2>Value2</element2>
</root>

and a String variable myString.

Just going through with the methods startElement, endElement() and characters() is easy. But I don't understand how I can achieve the following:

If the current element equals element1 store its value value1 in myString. As far as I understand there is nothing like:

if (qName.equals("element1")) myString = qName.getValue();

Guess I'm just thinking too complicated :-)

Robert

like image 681
Robert Strauch Avatar asked Nov 07 '10 21:11

Robert Strauch


1 Answers

This solution works for a single element with text content. When element1 has more sub-elements some more work is needed. Brian's remark is a very important one. When you have multiple elements or want a more generic solution this might help you. I tested it with a 300+MB xml file and it's still very fast:

final StringBuilder builder=new StringBuilder();
XMLReader saxXmlReader = XMLReaderFactory.createXMLReader();

DefaultHandler handler = new DefaultHandler() {
    boolean isParsing = false;

    public void startElement(String uri, String localName, String qName, Attributes attributes) {
        if ("element1".equals(localName)) {
            isParsing = true;
        }
        if (isParsing) {
            builder.append("<" + qName + ">");
        }
    }

    @Override
    public void characters(char[] chars, int i, int i1) throws SAXException {
        if (isParsing) {
            builder.append(new String(chars, i, i1));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (isParsing) {
            builder.append("</" + qName + ">");
        }
        if ("element1".equals(localName)) {
            isParsing = false;
        }
    }
};

saxXmlReader.setContentHandler(handler);
saxXmlReader.setErrorHandler(handler);

saxXmlReader.parse(new InputSource(new FileInputStream(input)));
like image 50
jvwilge Avatar answered Nov 14 '22 20:11

jvwilge