0
我有一個包含文本'The f'
一個節點:如何使用Nokogiri獲取包含文本的當前節點之前的第一個節點?
<w:r w:rsidR="00BC78BF">
<w:t>e takes out his phone and calls a friend.</w:t>
</w:r>
<w:r w:rsidR="00CB49B6">
<w:t xml:space="preserve"/>
</w:r>
<w:ins w:author="Mitchell Gould" w:date="2016-11-14T14:23:00Z" w:id="8">
<w:r w:rsidR="00BC7F15">
<w:t>The f</w:t>
</w:r>
</w:ins>
我想要得到的文本中第一次出現這種文本節點之前存在。
我嘗試使用:
node.previous_element.text
=> " "
和
previous_node = node.xpath('preceding-sibling::w:r').last
=> " "
這是因爲有時previous_element
只是如上所示的空間,並且可能的是,可能有許多這些元素的那只是空間。
我怎樣才能得到包含文本的第一個兄弟姐妹?
require 'nokogiri'
doc = Nokogiri::XML(<<EOT)
<xml>
<r>
<t>e takes out his phone and calls a friend.</t>
</r>
<r>
<t/>
</r>
<ins>
<r>
<t>The f</t>
</r>
</ins>
</xml>
EOT
doc.search('//text()').map { |t| t.text.strip }.reject(&:empty?)
# => ["e takes out his phone and calls a friend.", "The f"]
然後它變成識別元素之前"The f"
一個問題,我會離開爲你一個任務:
你期望得到什麼? 「e拿出他的電話,給朋友打電話。」?你在Code_中嘗試過什麼? – mudasobwa
我更新了我的問題以顯示我所嘗試的內容。是的,我希望得到「」e取出他的電話,並打電話給朋友。「 – chell
獲取'w:t'節點的集合並向後迭代一次以獲取_previous'w:t' element_。遞歸'previous_element',除非它的'text'屬性不爲空 – mudasobwa