根据Nokogiri中的其他属性获取某些属性?

时间:2012-09-25 20:17:46

标签: ruby xml nokogiri

这是我正在使用的XML:

<order xmlns="http://example.com/schemas/1.0">
  <link type="application/xml" rel="http://example.com/rel/self" href="https://example.com/orders/1631"/>
  <link type="application/xml" rel="http://example.com/rel/order/history" href="http://example.com/orders/1631/history"/>
  <link type="application/xml" rel="http://example.com/rel/order/transition/release" href="https://example.com/orders/1631/release"/>
  <link type="application/xml" rel="http://example.com/rel/order/transition/cancel" href="https://example.com/orders/1631/cancel"/>
  <state>hold</state>
  <order-number>123-456-789</order-number>
  <survey-title>Testing</survey-title>
  <survey-url>http://example.com/s/123456</survey-url>
  <number-of-questions>6</number-of-questions>
  <number-of-completes>100</number-of-completes>
  <target-group>
    <country>
      <id>US</id>
      <name>United States</name>
    </country>
    <min-age>15</min-age>
  </target-group>
  <quote>319.00</quote>
  <currency>USD</currency>
</order>

我需要做的是从href link

rel获取http://example.com/rel/order/transition/release属性

那么,我怎么能用Nokogiri呢?

2 个答案:

答案 0 :(得分:1)

易peasy:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<order xmlns="http://example.com/schemas/1.0">
  <link type="application/xml" rel="http://example.com/rel/self" href="https://example.com/orders/1631"/>
  <link type="application/xml" rel="http://example.com/rel/order/history" href="http://example.com/orders/1631/history"/>
  <link type="application/xml" rel="http://example.com/rel/order/transition/release" href="https://example.com/orders/1631/release"/>
  <link type="application/xml" rel="http://example.com/rel/order/transition/cancel" href="https://example.com/orders/1631/cancel"/>
  <state>hold</state>
  <order-number>123-456-789</order-number>
  <survey-title>Testing</survey-title>
  <survey-url>http://example.com/s/123456</survey-url>
  <number-of-questions>6</number-of-questions>
  <number-of-completes>100</number-of-completes>
  <target-group>
    <country>
      <id>US</id>
      <name>United States</name>
    </country>
    <min-age>15</min-age>
  </target-group>
  <quote>319.00</quote>
  <currency>USD</currency>
</order>
EOT

href = doc.at('link[rel="http://example.com/rel/order/transition/release"]')['href']
=> "https://example.com/orders/1631/release"

这是使用Nokogiri使用CSS访问器的能力。有时使用XPath更简单(或唯一的方法),但我更喜欢CSS,因为它们往往更具可读性。

Nokogiri::Node.at可以使用CSS访问器或XPath,并返回匹配该模式的第一个节点。如果您需要迭代所有匹配项,请改用search,这将返回NodeSet,您可以将其视为数组。对于at_xpathat_css对称,Nokogiri还支持cssxpath以及atsearch

答案 1 :(得分:0)

这是一个单行:

@doc.xpath('//xmlns:link[@rel = "http://example.com/rel/order/transition/release"]').attr('href') 
相关问题