How to parse a kml/xml file in Java

Hi,

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

You can look at the kml file I am trying to parse by typing:

http://maps.google.com/maps/geo?q=Hofbrunnstrasse+39,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!

Sebastian.
String question = "http://maps.google.com/maps/geo?q=Hofbrunnstrasse+39,Munich,Germany&output=xml&key=abcdefg"
try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        try {
// Following line throws an exception of type:
//com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence.
 
            Document document = builder.parse(question);
        } catch (SAXException e) {
            e.printStackTrace();

Open in new window

WaschtelAsked:
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("http://maps.google.com/maps/geo?q=Hofbrunnstrasse+39,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
xmlStream.read(xmlBuffer);
 
//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

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