Cannot print localname in SAX DefaultHandler's startElement() method

45 views Asked by At
import java.io.FileInputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Sample1SAX {

    /**
     * @param args
     * @throws SAXException
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        SAXParserFactory myFactory = SAXParserFactory.newInstance();
        SAXParser sp = myFactory.newSAXParser();

        MyHandler sh = new MyHandler();
        sp.parse(new FileInputStream("test.xml"), sh);

    }

}

class MyHandler extends DefaultHandler {

    public void startDocument() {
        System.out.println("XML document parsing started.");
    }

    public void endDocument() {
        System.out.println("XML document parsing ended");
    }

    public void startElement(String namespaceURI, String localName,
            String qName, Attributes attrs) {

        System.out.println(localName + "+++++++++++++++++++++++++++");
        System.out.println("QName is " + qName);

    }

}

After running this program with the following xml file

<?xml version="1.0" encoding="UTF-8"?>
<mybook:book xmlns:mybook="http://www.test.mm/books">
    <mybook:title>Java Exercise Book</mybook:title>
    <mybook:price>$3000</mybook:price>
    <mybook:author xmlns:people="http://www.test2.mm/person">
        <person:name>myname</person:name>
        <person:title>AAA</person:title>

    </mybook:author>


</mybook:book>

My output is XML document parsing started. +++++++++++++++++++++++++++ QName is mybook:book +++++++++++++++++++++++++++ QName is mybook:title +++++++++++++++++++++++++++ QName is mybook:price +++++++++++++++++++++++++++ QName is mybook:author +++++++++++++++++++++++++++ QName is person:name +++++++++++++++++++++++++++ QName is person:title XML document parsing ended

According to this output although QName can be printed, I cannot print localName. I would like to know why I cannot print the localName.

1

There are 1 answers

0
Sandi On

Now I know how to print the localName. I insert the following statement after creating SAXParserFactory instance as follow:

SAXParserFactory myFactory = SAXParserFactory.newInstance(); myFactory.setNamespaceAware(true);

My output is :

XML document parsing started.

book+++++++++++++++++++++++++++ QName is mybook:book

title+++++++++++++++++++++++++++ QName is mybook:title

price+++++++++++++++++++++++++++ QName is mybook:price

author+++++++++++++++++++++++++++ QName is mybook:author