Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace handling with SAX in Java

Consider the following input xml document:

<oracle:EMP xmlns:oracle="http://www.oracle.com/xml"/>

...and the following handler:

final class XMLizatorSaxHandler extends DefaultHandler {
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        System.out.println(uri + "," + localName + "," + qName);
    }
}

When using it with a SAXParser I would expect the following outupt:

uri: http://www.oracle.com/xml
localName: EMP
qName: oracle:EMP

But I get this instead:

uri:
localName:
qName: oracle:EMP

Why? How can I get correct information?

like image 491
lviggiani Avatar asked May 26 '26 17:05

lviggiani


1 Answers

Ok, thanks to Steve's hint I found the solution.

Need to call SaxParserFactory.setNamespaceAware(true); before SaxParserFactory.newSAXParser();

Here is full code:

SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true); // here is the trick

SAXParser parser = saxParserFactory.newSAXParser();
MyHandler handler = new MyHandler();

parser.parse(in, handler);
like image 186
lviggiani Avatar answered May 28 '26 07:05

lviggiani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!