2011-12-27 215 views
0

我試圖從Google使用天氣api獲取天氣數據並通過JDOM解析文檔。JDOM使用變音符號解析XML

這是我使用的代碼:

SAXBuilder builder = new SAXBuilder(); 
Document doc; 
URL url = new URL(GOOGLE_WEATHER_API); 
doc = builder.build(url);  
Element root = doc.getRootElement(); 
Element weather = root.getChild("weather"); 
List currentConditions = weather.getChildren("current_conditions"); 
... 

問題是,每當由谷歌返回的XML包含變音字符(U,A,O數...),我得到一個JDOMParseException

org.jdom.input.JDOMParseException: Error on line 1 of document http://www.google.de/ig/api?weather=Heidelberg&hl=en :
Fatal Error: com.sap.engine.lib.xml.parser.ParserException:
Incorrect encoded sequence detected at character (hex) 0x72, (bin) 1110010.
Check whether the input parsed contains correctly encoded characters.
Encoding used is: 'utf-8'(http://www.google.de/ig/api?weather=Heidelberg&hl=en, row:1, col:191):
Incorrect encoded sequence detected at character (hex) 0x72, (bin) 1110010.
Check whether the input parsed contains correctly encoded characters.
Encoding used is: 'utf-8' (http://www.google.de/ig/api?weather=Heidelberg&hl=en, row:1, col:191)

當我在瀏覽器中打開URL時,檢查編碼爲UTF-8的頁面屬性。所以我不知道爲什麼它不起作用。 有沒有人有想法?

最好的問候,保羅

+0

奇怪,我想不出除了可能什麼嘗試像Xerces的不同的XML解析器。我不知道com.sap.engine.lib.xml.parser。 – 2011-12-27 13:12:06

回答

1

從URL中的XML結果不包括在其XML頭的任何編碼。而是在http響應(ISO-8859-1)的Content-Type標頭上指定編碼。顯然,即使你將URL傳遞給jdom,它也不能正確處理它(它使用UTF-8,這是缺省編碼的xml)。你需要自己處理http響應(閱讀頭文件並將正確的編碼傳遞給jdom),或者使用可以爲你做的解析器(儘管我不知道任何標準的xml解析器)。

如果您使用的是標準的XML API,你會做這樣的事情:

HttpURLConnection = (HttpURLConnection)url.openConnection(); 
String encoding = ... // get encoding from http header 
InputSource source = new InputSpource(url.openStream()); 
source.setEncoding(encoding); 
DocumentBuilder db = ... // create doc builder 
Document doc = db.parse(source);