Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace: javax.xml.bind.UnmarshalException: unexpected element

For some reason I have to manually parse a KML file which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
    <Document>
        ...
       <Placemark>
           <Point><coordinates>13.38705,52.52715,0</coordinates></Point>
          <Name>My name</Name>
          <description xmlns="">Hallo World</description>
       </Placemark>
   </Document>
</kml>

For mapping it to java I wrote the following class

@XmlRootElement(name = "kml", namespace = "http://www.opengis.net/kml/2.2")
public class Kml {
// <kml xmlns="http://www.opengis.net/kml/2.2">
    Document document;

    @XmlElement(name = "Document")
    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }
 }

Using Jaxb I got the following parser.

public class JAXBKmlParser {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

public Kml klmParser(final String kmlFile) {

    Kml kml = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Kml.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        StringReader reader = new StringReader(kmlFile);
        kml = (Kml) unmarshaller.unmarshal(reader);

    } catch (JAXBException e) {
        logger.error("JABX Exception corrupted KML", e);
    }

    return kml;
    }
}

My problem is that the xml namespace attribute is not recognised.

If I change the annotation

 @XmlRootElement(name = "kml", namespace = "http://www.opengis.net/kml/2.2")

to

 @XmlRootElement(name = "kml")

and removing the namespace from the header of my KML file then the parsing works without any problem.

My question is how to cope this problem without removing the namespace.

Notice that the description tag has also a namespace.

like image 631
Luixv Avatar asked Dec 26 '22 09:12

Luixv


1 Answers

Since your XML document leverages a default namespace you should use the package level @XmlSchema annotation to map the namespace qualification. The @XmlSchema annotations is added to a special class called package-info that goes in the same package as the domain model and contains the following content. With @XmlSchema specified you won't need to specify any other namespace information.

package-info.java

@XmlSchema(
    namespace = "http://www.opengis.net/kml/2.2",
    elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

For More Information

You can read more about JAXB and namespaces on my blog:

  • http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
like image 149
bdoughan Avatar answered Feb 13 '23 02:02

bdoughan