在rails中进行Xml解析(Xml parsing in rails)

编程入门 行业动态 更新时间:2024-10-28 11:20:00
rails中进行Xml解析(Xml parsing in rails)

我有这个XML数据:

<?xml version="1.0" encoding="UTF-8"?> <responseParam> <RESULT>-1</RESULT> <ERROR_CODE>509</ERROR_CODE> </responseParam>

如何才能获取错误代码的值? 我试过这个:

result = Net::HTTP.get(URI.parse(otpUrl)) data = Hash.from_xml(result) puts "#{data['ERROR_CODE']}" puts data[:ERROR_CODE]

只打印“数据”给我整个哈希。 我无法仅获得ERROR_CODE的值。

有帮助吗?

I have this XML data:

<?xml version="1.0" encoding="UTF-8"?> <responseParam> <RESULT>-1</RESULT> <ERROR_CODE>509</ERROR_CODE> </responseParam>

How can I fetch the value of error code only? I have tried this :

result = Net::HTTP.get(URI.parse(otpUrl)) data = Hash.from_xml(result) puts "#{data['ERROR_CODE']}" puts data[:ERROR_CODE]

printing only "data" gives me the whole hash. I am not able to get only the value of ERROR_CODE.

Any help ?

最满意答案

你可以在这里使用Nokigiri 。 假设这是你的error.xml

<?xml version="1.0" encoding="UTF-8"?> <responseParam> <RESULT>-1</RESULT> <ERROR_CODE>509</ERROR_CODE> </responseParam>

你可以这样做: -

@doc = Nokogiri::XML(File.open("error.xml")) @doc.xpath("//ERROR_CODE") will give you something like:- # => ["<ERROR_CODE>509</ERROR_CODE>]"

Node方法xpath和css实际上返回一个NodeSet ,它非常像一个array ,并包含来自文档的匹配节点。

you can use Nokigiri here. suppose this is your error.xml

<?xml version="1.0" encoding="UTF-8"?> <responseParam> <RESULT>-1</RESULT> <ERROR_CODE>509</ERROR_CODE> </responseParam>

you can do something like:-

@doc = Nokogiri::XML(File.open("error.xml")) @doc.xpath("//ERROR_CODE") will give you something like:- # => ["<ERROR_CODE>509</ERROR_CODE>]"

The Node methods xpath and css actually return a NodeSet, which acts very much like an array, and contains matching nodes from the document.

更多推荐

本文发布于:2023-08-03 18:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:rails   Xml   parsing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!