2012-09-25 197 views
0

這裏是我的工作的XML:根據Nokogiri中的其他屬性獲取某些屬性?

<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屬性,從具有linkhttp://example.com/rel/order/transition/release

所以一個rel,我該怎麼辦,使用引入nokogiri?

回答

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,您可以將其視爲數組。 Nokogiri還支持at_xpathat_css以及cssxpath對於atsearch對稱性。

0

這是一個班輪:

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

要小心。 Nokogiri的'xpath'返回一個NodeSet,它實際上是一個數組。如果多個節點與搜索匹配,從數組中獲取'attr'將不會爲您提供您期望的結果。例如,刪除'rel'的字符串匹配,只查找'@ rel'。你會得到第一個結果。最好使用'at'搜索,或者使用數組索引來指定您想要的NodeSet的哪個元素。 –

+0

正確。我認爲提供的XML是規範的。對於一個通用的解決方案,你的是一個參考。 –