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.
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:
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