groovy – 解析xml的问题

groovy – 解析xml的问题,第1张

概述我是Groovy的新手,我正在尝试解析有效​​的休息资源和无效资源. 例如: 这段代码工作正常 – def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdot.xml')println entity.name()println entity.screen_name.text() 当我运行它时 @H_502_1@ 我是Groovy的新手,我正在尝试解析有效​​的休息资源和无效资源.
例如:

这段代码工作正常 –

def entity = new XmlSlurper().parse('http://API.twitter.com/1/users/show/slashdot.xml')println entity.name()println entity.screen_name.text()

当我运行它时,我得到输出:

userslashdot

但是当我将无效的url传递给xmlSlurper时,就像这样

def entity = new XmlSlurper().parse('http://API.twitter.com/1/users/show/slashdotabc.xml')println entity.name()println entity.screen_name.text(

)

我收到此错误消息:

Caught: java.io.fileNotFoundException: http://API.twitter.com/1/users/show/slashdotabc.xml    at xmltest.run(xmltest.groovy:1)

虽然url返回一个哈希代码(如下所示),但是我想解析并显示它.

<hash><request>/1/users/show/slashdotabc.xml</request><error>Not found</error></hash>

如何解析返回404但有错误信息的URL?

任何帮助将不胜感激.


谢谢&问候,
弗兰克科弗特

解决方法 您想要查看的响应可以在URL连接的errorStream而不是inputStream中找到.幸运的是,给定inputStream,XmlSlurper.parse也可以读取inputStream.

这是一个示例,当您没有获得200状态时切换到读取errorStream:

def con = new URL("http://API.twitter.com/1/users/show/slashdotaxxxbc.xml").openConnection()def xml = new XmlSlurper().parse(con.responseCode == 200 ? con.inputStream : con.errorStream)
总结

以上是内存溢出为你收集整理的groovy – 解析xml的问题全部内容,希望文章能够帮你解决groovy – 解析xml的问题所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1231529.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存