簡體   English   中英

Nokogiri在Rails中使用XPath解析Rackspace返回

[英]Nokogiri parsing Rackspace return using XPath in Rails

我正在使用Nokogiri解析來自Rackspace API的返回值,因此我正在使用其示例代碼來

   response = server.get '/customers/'+@user.customer_id.to_s+'/domains/', server.xml_format
   doc = Nokogiri::XML::parse response.body
   puts "xpath values"
   doc.xpath("//name").each do |node|
   puts
     node.text
   end

作為我使用Nokogiri返回元素節點節點列表的代碼

由於某種原因,我似乎錯過了一些顯而易見的事情,而我一生都無法獲取它來解析節點列表並將其返回給我,我可以做些簡單的事情來修復它使其返回節點列表嗎? ?

這是我要解析的XML的示例:

   <domainList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList">
  <offset>0</offset>
  <size>50</size>
  <total>4</total>
  <domains>
    <domain>
      <name>domain1.com</name>
      <accountNumber>xxxxxxx</accountNumber>
      <serviceType>exchange</serviceType>
    </domain>
    <domain>
      <name>domain2.com</name>
      <accountNumber>xxxxxxx</accountNumber>
      <serviceType>exchange</serviceType>
    </domain>
    <domain>
      <name>domain3.com</name>
      <accountNumber>xxxxxxx</accountNumber>
      <serviceType>exchange</serviceType>
    </domain>
  </domains>
</domainList>

干杯

問題似乎是您必須告訴Nokogiri他們的名稱空間。

如果您刪除xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList"您可以通過domainLists標記中的xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList"來查看查詢。

否則,您需要向Nokogiri告知該名稱空間。

doc.xpath("//blarg:name", {'blarg' => 'urn:xml:domainList'}).each do |name|
  puts name.text
end

Nokogiri xpath使用第二個參數,它是名稱空間的哈希。 您擁有的xml定義了通用名稱空間,但未為其提供標簽。 我不知道nokogiri是否有辦法找到它,所以在您的搜索中,只是給您的搜索一個任意標記,然后將名稱空間路徑與此標記關聯。 您可以輸入所需的任何文本,而不是blarg,僅用於示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM