Convert MRC data format to MARC XML.

    Args:
        mrc (str): MRC as string.

    Returns:
        str: XML with MARC.
541376
def mrc_to_marc(mrc):
    
    # ignore blank lines
    lines = [
        line
        for line in mrc.splitlines()
        if line.strip()
    ]

    def split_to_parts(lines):
        for line in lines:
            first_part, second_part = line.split(" L ", 1)

            yield line, first_part, second_part.lstrip()

    control_lines = []
    data_lines = []
    for line, first_part, second_part in split_to_parts(lines):
        if second_part.startswith("$"):
            data_lines.append(line)
        else:
            control_lines.append(line)

    # convert controlfield lines
    record = MARCXMLRecord()
    record.oai_marc = True
    for line, descr, content in split_to_parts(control_lines):
        record.controlfields[descr.strip()[:3]] = content

    def get_subfield_dict(line):
        fields = (
            (field[0], field[1:])
            for field in line.split("$$")[1:]
        )

        fields_dict = defaultdict(list)
        for key, val in fields:
            fields_dict[key].append(val)

        return fields_dict

    # convert datafield lines
    for line, descr, content_line in split_to_parts(data_lines):
        name = descr[:3]
        i1 = descr[3]
        i2 = descr[4]

        record.add_data_field(
            name,
            i1,
            i2,
            get_subfield_dict(content_line)
        )

    return record.to_XML()
632443
def to_xml(self, opts = defaultdict(lambda: None)):
        '''
        
        '''
        if not self.launch_url or not self.secure_launch_url:
            raise InvalidLTIConfigError('Invalid LTI configuration')


        root = etree.Element('cartridge_basiclti_link', attrib = {
                    '{%s}%s' %(NSMAP['xsi'], 'schemaLocation'): 'http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd',
                    'xmlns': 'http://www.imsglobal.org/xsd/imslticc_v1p0'
                    }, nsmap = NSMAP)
        
        for key in ['title', 'description', 'launch_url', 'secure_launch_url']:
            option = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'], key))
            option.text = getattr(self, key)

        vendor_keys = ['name', 'code', 'description', 'url']
        if any('vendor_' + key for key in vendor_keys) or\
                self.vendor_contact_email:
                    vendor_node = etree.SubElement(root, '{%s}%s'
                            %(NSMAP['blti'], 'vendor'))
                    for key in vendor_keys:
                        if getattr(self, 'vendor_' + key) != None:
                            v_node = etree.SubElement(vendor_node,
                                    '{%s}%s' %(NSMAP['lticp'], key))
                            v_node.text = getattr(self, 'vendor_' + key)
                    if getattr(self, 'vendor_contact_email'):
                        v_node = etree.SubElement(vendor_node,
                                '{%s}%s' %(NSMAP['lticp'], 'contact'))
                        c_name = etree.SubElement(v_node,
                                '{%s}%s' %(NSMAP['lticp'], 'name'))
                        c_name.text = self.vendor_contact_name
                        c_email = etree.SubElement(v_node,
                                '{%s}%s' %(NSMAP['lticp'], 'email'))
                        c_email.text = self.vendor_contact_email

        # Custom params
        if len(self.custom_params) != 0:
            custom_node = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'],
                'custom'))
            for (key, val) in sorted(self.custom_params.items()):
                c_node = etree.SubElement(custom_node, '{%s}%s'
                        %(NSMAP['lticm'], 'property'))
                c_node.set('name', key)
                c_node.text = val

        # Extension params
        if len(self.extensions) != 0:
            for (key, params) in sorted(self.extensions.items()):
                extension_node = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'],
                    'extensions'), platform = key)
                self.recursive_options(extension_node,params)

        if getattr(self, 'cartridge_bundle'):
            identifierref = etree.SubElement(root, 'cartridge_bundle',
                    identifierref = self.cartridge_bundle)

        if getattr(self, 'cartridge_icon'):
            identifierref = etree.SubElement(root, 'cartridge_icon',
                    identifierref = self.cartridge_icon)

        return '<?xml version="1.0" encoding="UTF-8"?>' + etree.tostring(root)
34905
def toxml(self):
        

        xmlstr = '<OnCondition test="{0}"'.format(self.test)

        chxmlstr = ''

        for action in self.actions:
            chxmlstr += action.toxml()

        if chxmlstr:
            xmlstr += '>' + chxmlstr + '</OnCondition>'
        else:
            xmlstr += '/>'

        return xmlstr
1045996
def to_xml(el):
    
    sio = StringIO()
    el.export(sio, 0, name_='PcGts', namespacedef_='xmlns:pc="%s"' % NAMESPACES['page'])
    return '<?xml version="1.0" encoding="UTF-8"?>\n' + sio.getvalue()
566963
def _oai_to_xml(marc_oai):  # TODO: move this to MARC XML parser?
    
    record = MARCXMLRecord(marc_oai)
    record.oai_marc = False

    return record.to_XML()
1335374
def to_xml_string(str="")
      str << ('<c:' << tag_name.to_s << '>')
      if @f
        str << ('<c:' << @ref_tag_name.to_s << '>')
        str << ('<c:f>' << @f.to_s << '</c:f>')
      end
      @data.to_xml_string str
      if @f
        str << ('</c:' << @ref_tag_name.to_s << '>')
      end
      str << ('</c:' << tag_name.to_s << '>')
    end
48579
def to_xml(self):
        """"""
        element = etree.Element(self._tag_name)
        struct_to_xml(element, [
            {"author": self.handle},
            {"first_name": self.name},
            {"last_name": ""},  # We only have one field - splitting it would be artificial
            {"image_url": self.image_urls["large"]},
            {"image_url_small": self.image_urls["small"]},
            {"image_url_medium": self.image_urls["medium"]},
            {"gender": self.gender},
            {"bio": self.raw_content},
            {"location": self.location},
            {"searchable": "true" if self.public else "false"},
            {"nsfw": "true" if self.nsfw else "false"},
            {"tag_string": " ".join(["#%s" % tag for tag in self.tag_list])},
        ])
        return element
1271276
def to_xml_string(str = '')
      str << '<cfRule '
      serialized_attributes str
      str << '>'
      str << ('<formula>' << [*self.formula].join('</formula><formula>') << '</formula>') if @formula
      @color_scale.to_xml_string(str) if @color_scale && @type == :colorScale
      @data_bar.to_xml_string(str) if @data_bar && @type == :dataBar
      @icon_set.to_xml_string(str) if @icon_set && @type == :iconSet
      str << '</cfRule>'
    end
479273
def _add_namespace(marc_xml):
    
    dom = marc_xml

    if isinstance(dom, basestring):
        dom = dhtmlparser.parseString(marc_xml)

    root = dom.find("root")
    if root:
        root[0].params = {}

    for record in dom.find("record"):
        record.params = {}

    collections = dom.find("collection")
    if not collections:
        record = dom.find("record")[0]
        return XML_TEMPLATE.replace("$CONTENT", str(record))

    for col in collections:
        col.params["xmlns"] = "http://www.loc.gov/MARC21/slim"
        col.params["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance"
        col.params["xsi:schemaLocation"] = "http://www.loc.gov/MARC21/slim " + \
                   "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"

    return str(dom)
1020926
def to_xml_string(str = '')
      str << '<c:catAx>'
      super(str)
      str << ('<c:auto val="' << @auto.to_s << '"/>')
      str << ('<c:lblAlgn val="' << @lbl_algn.to_s << '"/>')
      str << ('<c:lblOffset val="' << @lbl_offset.to_i.to_s << '"/>')
      str << ('<c:tickLblSkip val="' << @tick_lbl_skip.to_s << '"/>')
      str << ('<c:tickMarkSkip val="' << @tick_mark_skip.to_s << '"/>')
      str << '</c:catAx>'
    end
272327
def _cat_pt_xml(self):
        
        xml = ''
        for idx, category in enumerate(self._series.categories):
            xml += (
                '                <c:pt idx="{cat_idx}">\n'
                '                  <c:v>{cat_label}</c:v>\n'
                '                </c:pt>\n'
            ).format(**{
                'cat_idx':   idx,
                'cat_label': escape(to_unicode(category.label)),
            })
        return xml
5152
def to_xml_string(str = '')
      super(str) do
        # needs to override the super color here to push in ln/and something else!
        if color
          str << '<c:spPr><a:solidFill>'
          str << ('<a:srgbClr val="' << color << '"/>')
          str << '</a:solidFill>'
          str << '<a:ln><a:solidFill>'
          str << ('<a:srgbClr val="' << color << '"/></a:solidFill></a:ln>')
          str << '</c:spPr>'
          str << '<c:marker>'
          str << '<c:spPr><a:solidFill>'
          str << ('<a:srgbClr val="' << color << '"/>')
          str << '</a:solidFill>'
          str << '<a:ln><a:solidFill>'
          str << ('<a:srgbClr val="' << color << '"/></a:solidFill></a:ln>')
          str << '</c:spPr>'
          str << '</c:marker>'
        end
        if ln_width
          str << '<c:spPr>'
          str << '<a:ln w="' << ln_width.to_s << '"/>'
          str << '</c:spPr>'
        end
        @xData.to_xml_string(str) unless @xData.nil?
        @yData.to_xml_string(str) unless @yData.nil?
        str << ('<c:smooth val="' << ((smooth) ? '1' : '0') << '"/>')
      end
      str
    end
378559
def toxml(self):
        

        return '<DerivedParameter name="{0}"'.format(self.name) +\
          (' dimension="{0}"'.format(self.dimension) if self.dimension else '') +\
          (' value="{0}"'.format(self.value) if self.value else '') +\
          '/>'
896955
def val_to_mrc(code, val):
    
    code = str(code)
    if len(code) < 3:
        code += (3 - len(code)) * " "

    return "%s   L %s" % (code, val)
338719
def convert_to_python(self, xmlrpc=None):
        
        if xmlrpc:
            return xmlrpc.get(self.name, self.default)
        elif self.default:
            return self.default
        else:
            return None
729697
def item_to_mrc(code, val):
    
    if isinstance(val, basestring):
        return [val_to_mrc(code, val)]

    if isinstance(val, dict):
        val = [val]

    return dicts_to_mrc(code, val)
567052
def xml(self):
        
        rels_elm = CT_Relationships.new()
        for rel in self.values():
            rels_elm.add_rel(
                rel.rId, rel.reltype, rel.target_ref, rel.is_external
            )
        return rels_elm.xml