-1

私が使用している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

では、どうすればのこぎりを使ってそれを行うことができますか?

4

2 に答える 2

1

簡単-簡単:

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"

これは、CSSアクセサーを使用するNokogiriの機能を使用しています。XPathを使用する方が簡単な(または唯一の方法)場合もありますが、CSSの方が読みやすい傾向があるため、CSSの方が好きです。

Nokogiri::Node.atCSSアクセサーまたはXPathを使用でき、そのパターンに一致する最初のノードを返します。すべての一致を繰り返す必要がある場合は、代わりにを使用してください。これは、配列として扱うことができるsearchを返します。のこぎりはまた、対称性をサポートNodeSetat_xpathます。at_csscssxpathatsearch

于 2012-09-25T20:58:48.510 に答える
0

それはワンライナーです:

@doc.xpath('//xmlns:link[@rel = "http://example.com/rel/order/transition/release"]').attr('href') 
于 2012-09-25T21:04:27.923 に答える