Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalName is returning empty string, though namespace is defined

XML

<em:Employees  xmlns:em="http://www.example.com">
    <em:Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
        <childrens>
            <child>
                <age>2</age>
                <name>Guptha</name>
                <gender>Male</gender>
            </child>
        </childrens>
    </em:Employee>
</em:Employees>

Java

import java.io.File;
import java.io.IOException;
import java.util.List;

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

import org.xml.sax.SAXException;

public class XMLParserSAX {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();
        MyHandler handler = new MyHandler();
        saxParser.parse(new File("src/Resources/employees.xml"), handler);
        //Get Employees list
        List<Employee> empList = handler.getEmpList();
        //print employee information
        for (Employee emp : empList)
            System.out.println(emp);
    }
}

In my DefaultHandler, when I'm implementing startElement(), localName is empty, and qName contains the namespace including the name, ex. em:Employees.

If I'm not mistaken, localName should give me back the name without the namespace. Am I doing something wrong?

like image 505
samwell Avatar asked May 09 '26 00:05

samwell


1 Answers

Try making the SAXParserFactory namespace aware:

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    SAXParser saxParser = saxParserFactory.newSAXParser();

Read the details of startElement() here. You'll see that localNameisn' defined unless the parser is aware of namespaces.

like image 102
forty-two Avatar answered May 10 '26 12:05

forty-two



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!