Class: RMARC::MarcXmlWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/rmarc/marc_xml_writer.rb

Overview

Class for writing MARC record objects in MARC XML format.

The following example reads a file with MARC records and outputs the record set in MARC XML format:

writer = RMARC::MarcXmlWriter.new(STDOUT)
reader = RMARC::MarcStreamReader.new("file.mrc")
writer.start_document        
while reader.has_next
    record = reader.next()
    writer.write_record(record)
end
writer.end_document

See: www.loc.gov/standards/marcxml for more information about MARC XML.

Instance Method Summary collapse

Constructor Details

#initialize(output) ⇒ MarcXmlWriter

Default constructor.



45
46
47
# File 'lib/rmarc/marc_xml_writer.rb', line 45

def initialize(output)
  @output = output
end

Instance Method Details

#end_documentObject

Writes the collection end tag:

</collection>


111
112
113
# File 'lib/rmarc/marc_xml_writer.rb', line 111

def end_document
  @output.write("\n</collection>")
end

#start_document(encoding = nil) ⇒ Object

Writes the XML declaration and the collection start tag:

<?xml version='1.0' encoding='UTF-8'?>
<collection xmlns="http://www.loc.gov/MARC21/slim">

The default encoding is UTF-8.



55
56
57
58
59
60
61
62
63
64
# File 'lib/rmarc/marc_xml_writer.rb', line 55

def start_document(encoding = nil)
  decl = REXML::XMLDecl.new
  if encoding
    decl.encoding = encoding
  else
    decl.encoding = "UTF-8"
  end
  @output.write(decl)
  @output.write("\n<collection xmlns=\"http://www.loc.gov/MARC21/slim\">")
end

#write_record(record) ⇒ Object

Writes a single record element:

<record>
  <leader>00714cam a2200205 a 4500</leader>
  <controlfield tag='001'>12883376</controlfield>
  ...
  <datafield tag='245' ind1='1' ind2='0'>
    <subfield code='a'>Summerland /</subfield>
    <subfield code='c'>Michael Chabon.</subfield>
  </datafield>
  ...
</record>


78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/rmarc/marc_xml_writer.rb', line 78

def write_record(record)
  @output.write("\n  ")
  rec = REXML::Element.new('record')
  ldr = REXML::Element.new('leader')
  ldr.add_text(record.leader.to_s)
  rec.add_element(ldr)
  
  record.fields.each { |field| 
    if field.tag.to_i < 10
      fld = REXML::Element.new('controlfield')
      fld.add_attribute('tag', field.tag)
      fld.add_text(field.data)
      rec.add_element(fld)
    else
      fld = REXML::Element.new('datafield')
      fld.add_attribute('tag', field.tag)
      fld.add_attribute('ind1', field.ind1)
      fld.add_attribute('ind2', field.ind2)
      field.subfields.each { |subf| 
        sub = REXML::Element.new('subfield')
        sub.add_attribute('code', subf.code)
        sub.add_text(subf.data)
        fld.add_element(sub)
      }
      rec.add_element(fld)
    end
  }
  rec.write(@output, 1)
end