【问题标题】:Searching savon response as nokogiri document returns an empty array搜索 savon 响应作为 nokogiri 文档返回一个空数组
【发布时间】:2025-12-31 08:20:13
【问题描述】:

我尝试将 savon 的响应解析为 nokokiri 文档

c = Savon.client(wsdl: 'http://test.fedresurs.ru/MessageService/WebService.svc?wsdl', digest_auth: ['demowebuser', 'Ax!761BN'], namespace: "http://tempuri.org/", namespace_identifier: :tem, log: true)
r = c.call(:get_trade_messages, message: {'tem:startFrom' => DateTime.now-1})
r.doc.search("TradePlace")

它返回一个空数组。

我做错了什么?也许我应该以某种方式处理名称空间?但是,如何?我在 nokogiri 文档中找到的示例使用 Xpath,而不是搜索。即使使用 Xpath,它也会返回一个空数组。

XML 响应:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <GetTradeMessagesResponse xmlns="http://tempuri.org/">
         <GetTradeMessagesResult>
            <TradePlace INN="7606055642" Name="Первая электронная площадка " Site="1torgi.ru " OwnerName="ООО &quot;Промтех&quot;">
               <TradeList>
                  <Trade ID_External="ЗКОФЦП-17136" ID_EFRSB="653476">
                     <MessageList>
                        <TradeMessage ID="4851134"/>
                        <TradeMessage ID="4851135"/>
                     </MessageList>
                  </Trade>
               </TradeList>
            </TradePlace>
         </GetTradeMessagesResult>
      </GetTradeMessagesResponse>
   </s:Body>
</s:Envelope>

【问题讨论】:

  • 您是否尝试过使用 SoapUI 执行 SOAP 请求?这应该始终是您的第一个测试。 SoapUI 是否返回预期结果?
  • @SteffenRoller 当然,响应结果没问题。

标签: ruby xml xml-parsing nokogiri savon


【解决方案1】:

您可以使用Nokogiri 来分解 XML 响应。 一个(现在没有功能的)例子是这样的:

doc = Nokogiri::XML(response.to_hash[:get_quote_response][:get_quote_result])
print doc.to_xml(indent: 2)

print "Date      : ", doc.at_css("Date").text, "\n"
print "Last price: ", doc.at_css("Last").text

在我的 pastebin https://pastebin.com/W0RUuaHU 中有更完整的示例。不幸的是,WebserviceX 已停产。

【讨论】:

  • 好主意,但不工作,不知道如何用 nokogiri 解析哈希。你知道吗?
  • 您在谈论 XML 解构,这就是我提出 Nokogiri 的原因。我假设你已经用.to_hash 把你的结果变成了一个散列,并用awesome_print 打印?这就是我通过未知数据结构的方式。
  • 从我的回复中可以看出,我首先从哈希创建 XML 结构,然后然后使用 Nokogiri 使用 CSS 语法查找元素。
【解决方案2】:

正如我所料,答案在命名空间中,下面的代码可以正常工作:

r.doc.search("a|TradePlace", {"a" => "http://tempuri.org/"})

【讨论】: