Nokogiri:如何从XML::元素中检索文本,从它的后代元素中排除文本



是否有更优雅的方式来编写以下代码?

def get_text(element)
  text_node = element.children.find &:text?
  text_node.text if text_node
end

你可以写

element.xpath('text()').to_s

返回element的文本子元素的原始文本,不包括后代节点中的任何文本(而您的代码仅返回element的第一个文本子元素)。

请记住,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 textn    n  n"

如果你不介意:

a_node = Nokogiri::XML.fragment(doc.at('a').to_xml)
a_node.at('b').remove
a_node.text #=> "some textn    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

最新更新