如何使用 Nokogiri 在某些标签之后或之前获取文本 [英] How to get text after or before certain tags using Nokogiri
本文介绍了如何使用 Nokogiri 在某些标签之后或之前获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 HTML 文档,如下所示:
I have an HTML document, something like this:
<root><template>title</template>
<h level="3" i="3">Something</h>
<template element="1"><title>test</title></template>
# one
# two
# three
# four
<h level="4" i="5">something1</h>
some random test
<template element="1"><title>test</title></template>
# first
# second
# third
# fourth
<template element="2"><title>testing</title></template>
我想提取:
# one
# two
# three
# four
# first
# second
# third
# fourth
</root>
换句话说,我想要<template element="1"><title>test</title></template>
之后和下一个标签之前的所有文本在那之后开始."
In other words, I want "all text after <template element="1"><title>test</title></template>
and before the next tag that starts after that."
我可以使用 '//root/text()'
获取 root 之间的所有文本,但是如何获取某些标签前后的所有文本?
I can get all text between root using '//root/text()'
but how do I get all text before and after certain tags?
推荐答案
这似乎有效:
require 'nokogiri'
xml = '<root>
<template>title</template>
<h level="3" i="3">Something</h>
<template element="1">
<title>test</title>
</template>
# one
# two
# three
# four
<h level="4" i="5">something1</h>
some random test
<template element="1">
<title>test</title>
</template>
# first
# second
# third
# fourth
<template element="2">
<title>testing</title>
</template>
</root>
'
doc = Nokogiri::XML(xml)
text = (doc / 'template[@element="1"]').map{ |n| n.next_sibling.text.strip.gsub(/\n +/, "\n") }
puts text
# >> # one
# >> # two
# >> # three
# >> # four
# >> # first
# >> # second
# >> # third
# >> # fourth
这篇关于如何使用 Nokogiri 在某些标签之后或之前获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文