我有一个HTML文档,如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
我想提取:
# one
# two
# three
# four
# first
# second
# third
# fourth
</root>
Run Code Online (Sandbox Code Playgroud)
换句话说,我想要"在之后<template element="1"><title>test</title></template>
开始的下一个标记之前和之后的所有文本."
我可以在root之间获取所有文本,'//root/text()'
但如何在某些标记之前和之后获取所有文本?
这似乎有效:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2774 次 |
最近记录: |