在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.
更多推荐
发布评论