Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何从API请求解析XML节点?_Ruby_Xml_Api_Parsing_Nokogiri - Fatal编程技术网

Ruby 如何从API请求解析XML节点?

Ruby 如何从API请求解析XML节点?,ruby,xml,api,parsing,nokogiri,Ruby,Xml,Api,Parsing,Nokogiri,如何保存从API获得的XML页面中的信息 URL为“”,它返回: <OperatorDataContract xmlns="http://psgi.pts.se/PTS_Number_Service" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Name>Tele2 Sverige AB</Name> <Number>8-6785503</Number> </

如何保存从API获得的XML页面中的信息

URL为“”,它返回:

<OperatorDataContract xmlns="http://psgi.pts.se/PTS_Number_Service" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Tele2 Sverige AB</Name>
  <Number>8-6785503</Number>
</OperatorDataContract>

除了您的代码不是有效的Ruby之外,您还使它变得比必要的困难得多,至少对于一个简单的刮取和保存:

require 'nokogiri'
require 'open-uri'

url = "http://api.pts.se/PTSNumberService/Pts_Number_Service.svc/pox/SearchByNumber?number=8-6785503"
doc = Nokogiri::XML(open(url))

File.open("exported.txt", "w") do |file|
  name = doc.at('Name').text
  number = doc.at('Number').text
  file.puts name
  file.puts number
end
运行该命令将生成一个名为“exported.txt”的文件,该文件包含:

Tele2 Sverige AB
8-6785503

您可以根据需要进一步了解。

我想这就是您需要的。我确实读过,但没有看到最后一条。Thx很高兴它起了作用。处理HTML、XHTML和XML可能会令人沮丧,尤其是使用带有名称空间的XML。Nokogiri提供了许多功能,可以更轻松地导航和定位您想要的内容。其中之一是它能够使用CSS来选择节点,而不是XPath。虽然XPath的功能更强,但它也更复杂,所以为了可读性,我从CSS开始,然后在必要时切换到XPath。其他人更熟悉它,所以他们只使用它。这就是Nokogiri的魅力所在,它允许我们做出这些选择。我将研究css选择器并了解这一点。我希望你能看看我的另一个问题。我不理解将表中的值传递给变量的逻辑。[链接]我的想法是对的还是我错过了一些东西?嗨,再一次,很抱歉打扰你“锡人”,但我对这件事视而不见,我不知道为什么我不能让它在这里工作。我做错了什么?
Tele2 Sverige AB
8-6785503