gpt4 book ai didi

java - 在java中解析xml时出错

转载 作者:数据小太阳 更新时间:2023-10-29 02:22:50 25 4
gpt4 key购买 nike

我试图解析由 Google Geo 代码 API 返回的 XML,但在解析时出现以下错误..

 [Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at test2.main(test2.java:55)

amd 我的代码是这样的..我确定我正确地得到了响应 xml..

        URL u = new URL("https://maps.googleapis.com/maps/api/geocode/xml?latlng=12.983333,77.583333&sensor=false");  
URLConnection uc = u.openConnection();
uc.setDoOutput(true);

StringBuffer sbuf=new StringBuffer();

inxml=uc.getInputStream();

BufferedReader in = new BufferedReader(
new InputStreamReader(inxml));

String res;
//System.out.println(" Response from Google Maps "+res);
while ((res = in.readLine()) != null){
sbuf.append(res).append("\n");
}
in.close();

System.out.println(" Total Data received "+sbuf);

//XML PARSE Starts Here........

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

Document doc = docBuilder.parse(inxml);

// normalize text representation
doc.getDocumentElement ().normalize();

// System.out.println("Root element of the doc is "+doc.getDocumentElement().getNodeName());

}
catch(Exception e)
{
e.printStackTrace();
}

请建议 mw 对此提供一些帮助..

谢谢你。

最佳答案

问题出在你的调试代码上。您阅读文档以在此处显示 xml

while ((res = in.readLine()) != null){
sbuf.append(res).append("\n");
}

它使流通过所有数据,然后您尝试使用解析器再次读取它。

如果您删除调试代码,它应该可以工作。

关于java - 在java中解析xml时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5482154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com