ruby - Nokogiri:如何从 XML::Element 检索文本,排除其后代中的文本?

标签 ruby xpath nokogiri

下面的代码有更优雅的写法吗?

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

最佳答案

你可以写

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

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

关于ruby - Nokogiri:如何从 XML::Element 检索文本,排除其后代中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6651717/

相关文章:

ruby-on-rails - 如何使用 Controller 保存数组参数?

php - XPATH 检查属性是否包含多个值之一

python-3.x - 使用selenium和python滚动谷歌地图网页侧边栏

html - 你能用ruby nokogiri使用通配符搜索html属性吗

ruby - 如何避免 Nokogiri 编码 href 内容?

ruby - Nokogiri child 法

ruby - 如何将 IO 对象转换为 Ruby 中的字符串?

mysql - 将邮件消息解析为ruby中的数据库

php - Ruby On Rails 服务容器

xml - 为什么XSLT不喜欢我的XPath查询?