2011-12-27 137 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);