Search code examples
androidkmlsaxparser

Root element name does not match. Expected


I am parsing an KML file using Android simplified version of the SAX API in which there is no handler. The issue is that my call to

RootElement root = new RootElement("kml");

is crashing giving me an error like this:

java.lang.RuntimeException: android.sax.BadXmlException: Line 2: Root element name does not match. Expected: 'kml', Got: 'http://www.opengis.net/kml/2.2:kml'

This is the beginning of the file being parsed:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">  etc...

I am going by the book, but still it is causing the error. I have seen other post at stack overflow on this but they relate to SAXParserFactory where you can disable XML Schema validation. Unfortunately, in here I cannot.

Thanks!


Solution

  • Need to specify the KML namespace in your RootElement to match what's in the KML file otherwise will get a parse exception. Not specifying a namespace is technically a special namespace that has an empty URI.

    final String KML_NAMESPACE = "http://opengis.net/kml/2.2";
    RootElement root = new RootElement(KML_NAMESPACE, "kml");
    // ...
    XMLReader reader = ...;
    reader.setContentHandler(root.getContentHandler());
    reader.parse(...);