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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With