提取两个标签之间的文本以及标签中指定的属性的最简单方法是什么,例如:
some random text here
<tag id="12345">tag content A</tag>
some other random text
<tag type="mytype">
tag content B
</tag>
some more random text
这样我就可以得到一个列表
[{"id": "12345", "tag": "tag content A"},
{"type": "mytype", "tag": "tag content B"}]
每个标签都是一行,但开始和结束标签之间的内容可以有多行。
谢谢!
答案 0 :(得分:1)
“最简单”是一个见仁见智的问题,但我会做的是将整个事情包装成 XML 并使用 Nokogiri 来完成工作。
让我们使用您的示例:
s = <<-HERE
some random text here
<tag id="12345">tag content A</tag>
some other random text
<tag type="mytype">
tag content B
</tag>
some more random text
HERE
那么:
require 'nokogiri'
doc = Nokogiri.parse("<root>#{s}</root>")
arr = []
doc.xpath('/root/*').each do |tag|
att = tag.attributes.keys[0]
arr << {att => tag[att], tag.name => tag.content.strip}
end
现在 arr
是:
[{"id"=>"12345", "tag"=>"tag content A"},
{"type"=>"mytype", "tag"=>"tag content B"}]