如何用nokogiri构建器分解常见标签?

时间:2010-05-13 23:04:48

标签: xml ruby nokogiri

我想创建几个带有常用标签的构建器,以便拥有xml文档:

  <xml version="1.0"?>
    <a_kind_of_root>
      <!-- This part is common -->
      <event_date>20100514</event_date>
      <event_id>123</event_id>
      <event_type>Conference</event_type>
      <!-- This part is specific to the builder -->
      <my_tag>some text</my_tag>
    </a_kind_of_root>
  </xml>

  <xml version="1.0"?>
    <another_kind_of_root>
      <!-- This part is common -->
      <event_date>20100514</event_date>
      <event_id>123</event_id>
      <event_type>Conference</event_type>
      <!-- This part is specific to the builder -->
      <my_other_tag>some integer</my_other_tag>
    </another_kind_of_root>
  </xml>

我不知道如何将公共部分放在Nokogiri :: XML :: Builder

由于

1 个答案:

答案 0 :(得分:1)

您可以将Builder传递给方法&amp;有这个方法添加您的公共事件信息:

def event_tags(xml, ev=Hash.new)
  xml.event_date = ev[:date]
  xml.event_id = ev[:id]
  xml.event_type = ev[:type]
end

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    event_tags xml, :date => get_date, :id => get_id, :type => get_type
    # blah blah
  }
end