代码之家  ›  专栏  ›  技术社区  ›  Heuristic

Ruby:提取标签和标签属性之间的文本?

  •  0
  • Heuristic  · 技术社区  · 3 年前

    提取两个标记之间的文本以及标记中指定的属性的最简单方法是什么,例如:

    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 回复  |  直到 3 年前
        1
  •  1
  •   matt    3 年前

    “最简单”是一个观点问题,但我要做的是将整个过程打包为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"}]