2011-11-04 157 views
0

我有一個字符串:獲取兩個字符串之間的字符串?

<products type="array"> 
<product><brand>Rho2</brand> 
<created-at type="datetime">2011-11-03T21:29:46Z</created-at><id type="integer">78013</id><name>Test2</name> 
<price nil="true"/> 
<quantity nil="true"/> 
<sku nil="true"/> 
<updated-at type="datetime">2011-11-03T21:29:46Z</updated-at> 
</product> 
<product> 
<brand>Apple</brand> 
<created-at type="datetime">2011-10-26T21:26:59Z</created-at> 
<id type="integer">77678</id> 
<name>iPhone</name> 
<price>$199.99</price> 
<quantity>5</quantity> 
<sku>1234</sku> 
<updated-at type="datetime">2011-10-26T21:27:00Z</updated-at> 
</product> 

我想<brand></brand>之間的文本。

我想解析這個XML,收集標籤之間的數據。

+0

你寫「之間,並得到文本。 「 - 也許你錯過標籤名稱? – WarHog

+0

你的問題沒有多大意義。是否有理由不能僅僅使用任意數量的庫中的任何一個來解析XML,然後合理地檢索數據? – muffinista

+2

REXML或XmlSimple應該這樣做。是的,XML可以在一個字符串中,它仍然會解析。周圍有更多的圖書館。這裏有一個[工作示例](http://xml-simple.rubyforge.org/)。 – abhinav

回答

0

您應該使用您平臺中可用的任何XML解析器。然後你可以使用簡單的XPath表達式:

//brand 

它選擇在文檔中的所有元素brand

1

XmlSimple應該很容易。

require 'xmlsimple' 
products = XmlSimple.xml_in('<YOUR WHOLE XML>', { 'KeyAttr' => 'product' }) 
0

使用Ruby解析XML和HTML的事實標準是Nokogiri這些天:

require 'nokogiri' 

doc = Nokogiri::XML(<<EOT) 
<products type="array"> 
    <product> 
    <brand>Rho2</brand> 
    <created-at type="datetime">2011-11-03T21:29:46Z</created-at> 
    </product> 
    <product> 
    <brand>Apple</brand> 
    <created-at type="datetime">2011-10-26T21:26:59Z</created-at> 
    </product> 
</products> 
EOT 

puts doc.search('brand').map(&:text) 

,輸出:

Rho2 
Apple 
0
function getStringBetween(str , fromStr , toStr){ 
    var fromStrIndex = str.indexOf(fromStr) == -1 ? 0 : str.indexOf(fromStr) + fromStr.length; 
    var toStrIndex = str.slice(fromStrIndex).indexOf(toStr) == -1 ? str.length-1 : str.slice(fromStrIndex).indexOf(toStr) + fromStrIndex; 
    var strBtween = str.substring(fromStrIndex,toStrIndex); 
    return strBtween; 
} 
相關問題