How to parse a kml/xml file in Java


I'm trying to geocode an address with google maps.

You can look at the kml file I am trying to parse by typing:,Munich,Germany&output=xml&key=abcdefg

into your browser.

I try to create a DOM document from the kml file returned by the google maps server in Java, but I am  encountering problems when there are german "Umlaute (special characters like 'ä,'ö','ü')" in the kml response. Is there any way to parse the kml file differently, so I don't get an exception thrown?

Thanks for any help!

String question = ",Munich,Germany&output=xml&key=abcdefg"
try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
        try {
// Following line throws an exception of type:
// Invalid byte 2 of 2-byte UTF-8 sequence.
            Document document = builder.parse(question);
        } catch (SAXException e) {

Open in new window

Who is Participating?
WaschtelAuthor Commented:
I found a solution, although it is a bit verbose, and I don' t really understand why it works...

Maybe there's something shorter out there.

//Create a URL pointing to the Goole Maps gateway.
URL url = new URL(URLencoder.encode(",Munich,Germany&output=xml&key=abcdefg"
InputStream xmlStream = url.openStream()"),"UTF-8");
//Create a BuilderFactory
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
//Create a Builder
DocumentBuilder builder = builderFactory.newDocumentBuilder();
// Get the Stream
InputStream xmlStream = url.openStream();
//Measure the Stream and create a buffer
int size = xmlStream.available();
byte[] xmlBuffer=new byte[size];
//Fill the buffer with the Stream;
//Create a String from the Buffer using UTF-8 decoding
String xmlString = new String(xmlBuffer,Charset.forName("UTF-8"));
//Create a ByteArrayInputStream from the String
            ByteArrayInputStream xmlMassaged = new ByteArrayInputStream(xmlString.getBytes());
//Create a Document from this ByteArrayInputStream;
            document = builder.parse(xmlMassaged);

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.