次のコードを書くよりエレガントな方法はありますか?Nokogiri:テキストをその子孫から除外するXML :: Elementからテキストを取り出す方法は?
def get_text(element)
text_node = element.children.find &:text?
text_node.text if text_node
end
次のコードを書くよりエレガントな方法はありますか?Nokogiri:テキストをその子孫から除外するXML :: Elementからテキストを取り出す方法は?
def get_text(element)
text_node = element.children.find &:text?
text_node.text if text_node
end
あなたは(あなたのコードのみelement
の最初のテキスト子を返すのに対し)子孫ノード内の任意のテキストを除くelement
のテキスト子どもたちの生のテキストを返します
element.xpath('text()').to_s
を書くことができます。
あなたは子ノードを削除する必要があるので、DOMは階層的であることに注意してください:あなたは破壊的にそれをやってもかまわない場合
require 'nokogiri'
xml = <<EOT
<xml>
<a>some text
<b>
<c>more text</c>
</b>
</a>
</xml>
EOT
doc = Nokogiri::XML(xml)
:
はこれで始め
doc.at('b').remove
doc.text #=> "\n some text\n \n \n"
あなたが気に入ったら:
a_node = Nokogiri::XML.fragment(doc.at('a').to_xml)
a_node.at('b').remove
a_node.text #=> "some text\n \n "
後続のキャリッジリターンを取り除くといいですね。
of course this syntax will also help you
==================================
doc = Nokogiri::Slop <<-EOXML
<employees>
<employee status="active">
<fullname>Dean Martin</fullname>
</employee>
<employee status="inactive">
<fullname>Jerry Lewis</fullname>
</employee>
</employees>
EOXML
====================================
# navigate!
doc.employees.employee.last.fullname.content # => "Jerry Lewis"
fullname = @doc.xpath("//character")
puts fullname.text
nokogori.org: 'XMLは暴力のようなもので、問題が解決しなければ、十分に使い果たしていない。 – rubenvb