Generates an XML-formatted report for a single binding site
496818
def generate_xml(self):
        """"""
        report = et.Element('bindingsite')
        identifiers = et.SubElement(report, 'identifiers')
        longname = et.SubElement(identifiers, 'longname')
        ligtype = et.SubElement(identifiers, 'ligtype')
        hetid = et.SubElement(identifiers, 'hetid')
        chain = et.SubElement(identifiers, 'chain')
        position = et.SubElement(identifiers, 'position')
        composite = et.SubElement(identifiers, 'composite')
        members = et.SubElement(identifiers, 'members')
        smiles = et.SubElement(identifiers, 'smiles')
        inchikey = et.SubElement(identifiers, 'inchikey')

        # Ligand properties. Number of (unpaired) functional atoms and rings.
        lig_properties = et.SubElement(report, 'lig_properties')
        num_heavy_atoms = et.SubElement(lig_properties, 'num_heavy_atoms')
        num_hbd = et.SubElement(lig_properties, 'num_hbd')
        num_hbd.text = str(self.ligand.num_hbd)
        num_unpaired_hbd = et.SubElement(lig_properties, 'num_unpaired_hbd')
        num_unpaired_hbd.text = str(self.complex.num_unpaired_hbd)
        num_hba = et.SubElement(lig_properties, 'num_hba')
        num_hba.text = str(self.ligand.num_hba)
        num_unpaired_hba = et.SubElement(lig_properties, 'num_unpaired_hba')
        num_unpaired_hba.text = str(self.complex.num_unpaired_hba)
        num_hal = et.SubElement(lig_properties, 'num_hal')
        num_hal.text = str(self.ligand.num_hal)
        num_unpaired_hal = et.SubElement(lig_properties, 'num_unpaired_hal')
        num_unpaired_hal.text = str(self.complex.num_unpaired_hal)
        num_aromatic_rings = et.SubElement(lig_properties, 'num_aromatic_rings')
        num_aromatic_rings.text = str(self.ligand.num_rings)
        num_rot_bonds = et.SubElement(lig_properties, 'num_rotatable_bonds')
        num_rot_bonds.text = str(self.ligand.num_rot_bonds)
        molweight = et.SubElement(lig_properties, 'molweight')
        molweight.text = str(self.ligand.molweight)
        logp = et.SubElement(lig_properties, 'logp')
        logp.text = str(self.ligand.logp)

        ichains = et.SubElement(report, 'interacting_chains')
        bsresidues = et.SubElement(report, 'bs_residues')
        for i, ichain in enumerate(self.interacting_chains):
            c = et.SubElement(ichains, 'interacting_chain', id=str(i + 1))
            c.text = ichain
        for i, bsres in enumerate(self.bs_res):
            contact = 'True' if bsres in self.bs_res_interacting else 'False'
            distance = '%.1f' % self.min_dist[bsres][0]
            aatype = self.min_dist[bsres][1]
            c = et.SubElement(bsresidues, 'bs_residue', id=str(i + 1), contact=contact, min_dist=distance, aa=aatype)
            c.text = bsres
        hetid.text, chain.text, position.text = self.ligand.hetid, self.ligand.chain, str(self.ligand.position)
        composite.text = 'True' if len(self.lig_members) > 1 else 'False'
        longname.text = self.longname
        ligtype.text = self.ligtype
        smiles.text = self.ligand.smiles
        inchikey.text = self.ligand.inchikey
        num_heavy_atoms.text = str(self.ligand.heavy_atoms)  # Number of heavy atoms in ligand
        for i, member in enumerate(self.lig_members):
            bsid = ":".join(str(element) for element in member)
            m = et.SubElement(members, 'member', id=str(i + 1))
            m.text = bsid
        interactions = et.SubElement(report, 'interactions')

        def format_interactions(element_name, features, interaction_information):
            """Returns a formatted element with interaction information."""
            interaction = et.Element(element_name)
            # Sort results first by res number, then by distance and finally ligand coordinates to get a unique order
            interaction_information = sorted(interaction_information, key=itemgetter(0, 2, -2))
            for j, single_contact in enumerate(interaction_information):
                if not element_name == 'metal_complexes':
                    new_contact = et.SubElement(interaction, element_name[:-1], id=str(j + 1))
                else:  # Metal Complex[es]
                    new_contact = et.SubElement(interaction, element_name[:-2], id=str(j + 1))
                for i, feature in enumerate(single_contact):
                    # Just assign the value unless it's an atom list, use subelements in this case
                    if features[i] == 'LIG_IDX_LIST':
                        feat = et.SubElement(new_contact, features[i].lower())
                        for k, atm_idx in enumerate(feature.split(',')):
                            idx = et.SubElement(feat, 'idx', id=str(k + 1))
                            idx.text = str(atm_idx)
                    elif features[i].endswith('COO'):
                        feat = et.SubElement(new_contact, features[i].lower())
                        xc, yc, zc = feature
                        xcoo = et.SubElement(feat, 'x')
                        xcoo.text = '%.3f' % xc
                        ycoo = et.SubElement(feat, 'y')
                        ycoo.text = '%.3f' % yc
                        zcoo = et.SubElement(feat, 'z')
                        zcoo.text = '%.3f' % zc
                    else:
                        feat = et.SubElement(new_contact, features[i].lower())
                        feat.text = str(feature)
            return interaction

        interactions.append(format_interactions('hydrophobic_interactions', self.hydrophobic_features,
                                                self.hydrophobic_info))
        interactions.append(format_interactions('hydrogen_bonds', self.hbond_features, self.hbond_info))
        interactions.append(format_interactions('water_bridges', self.waterbridge_features, self.waterbridge_info))
        interactions.append(format_interactions('salt_bridges', self.saltbridge_features, self.saltbridge_info))
        interactions.append(format_interactions('pi_stacks', self.pistacking_features, self.pistacking_info))
        interactions.append(format_interactions('pi_cation_interactions', self.pication_features, self.pication_info))
        interactions.append(format_interactions('halogen_bonds', self.halogen_features, self.halogen_info))
        interactions.append(format_interactions('metal_complexes', self.metal_features, self.metal_info))

        # Mappings
        mappings = et.SubElement(report, 'mappings')
        smiles_to_pdb = et.SubElement(mappings, 'smiles_to_pdb')  # SMILES numbering to PDB file numbering (atoms)
        bsid = ':'.join([self.ligand.hetid, self.ligand.chain, str(self.ligand.position)])
        if self.ligand.atomorder is not None:
            smiles_to_pdb_map = [(key, self.ligand.Mapper.mapid(self.ligand.can_to_pdb[key],
                                                                mtype='protein', bsid=bsid)) for key in self.ligand.can_to_pdb]
            smiles_to_pdb.text = ','.join([str(mapping[0])+':'+str(mapping[1]) for mapping in smiles_to_pdb_map])
        else:
            smiles_to_pdb.text = ''

        return report
1079165
def xml(self, ilwdchar_to_hex = True):
    """"""
    if len(self.table) == 0:
      raise LIGOLwDBError, 'attempt to convert empty table to xml'
    ligolw = """\
<?xml version='1.0' encoding='utf-8' ?>
<?xml-stylesheet type="text/xsl" href="ligolw.xsl"?>
<!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt">
<LIGO_LW>
"""

    for tab in self.table.keys():
      try:
        ligolw += '   <Comment>'+self.strtoxml.xlat(self.table[tab]['query'])+'</Comment>\n'
      except KeyError:
        pass
      ligolw += '   <Table Name="'+tab+':table">\n'
      for col in self.table[tab]['orderedcol']:
        ligolw +='      <Column Name="'+tab.lower()+':'+col.lower()+'" Type="'+self.table[tab]['column'][col].lower()+'"/>\n'
      ligolw += '      <Stream Name="'+tab.lower()+':table" Type="Local" Delimiter=",">\n'
      stridx = 0
      ligolw += '      '
      for tup in self.table[tab]['stream']:
        if stridx != 0:
          ligolw += ',\n      '
        colidx = 0
        for tupi in tup:
          if tupi is not None:
            coltype = self.table[tab]['column'][self.table[tab]['orderedcol'][colidx]]
            if re.match(r'\Ailwd:char_u\Z',coltype):
              ligolw += '"'
              for ch in str(tupi):
                # NOTE: escape the backslash in the ilwd:char_u octal string
                ligolw += '\\\\%.3o' % (ord(ch))
              ligolw += '"'
            elif re.match(r'\Ailwd:char\Z',coltype):
              if ilwdchar_to_hex is True:
                # encode in DB2-style hex (e.g., "x'deadbeef'")
                ligolw += '"x\''
                for ch in str(tupi):
                  ligolw += "%02x" % ord(ch)
                ligolw += '\'"'
              else:
                ligolw += '"' + str(tupi) + '"'
            elif re.match(r'\Alstring\Z',coltype):
              # this santizes the contents of tupi in several ways: 
              # strtoxml.xlat escapes any double-quote and
              # backslash chars (with a preceding blackslash); and
              # then replaces <>& chars with their html
              # code equivalents
              # NOTE: string_format_func was removed so the enclosing ""
              # chars need to be added ourselves
              ligolw += '"'+self.strtoxml.xlat(tupi)+'"' 
            elif re.match(r'\Areal_4\Z',coltype):
              ligolw += '%13.7e' % tupi
            elif re.match(r'\Areal_8\Z',coltype):
              ligolw += '%22.16e' % tupi
            else:
              ligolw += str(tupi)
          else:
            ligolw += ''
          if colidx < (len(self.table[tab]['column']) - 1):
            ligolw += ','
          colidx += 1
        stridx += 1
      ligolw += '\n      </Stream>\n'
      ligolw += '   </Table>\n'
    ligolw += '</LIGO_LW>'

    return ligolw
86518
def _gen_xml(name,
             cpu,
             mem,
             diskp,
             nicp,
             hypervisor,
             os_type,
             arch,
             graphics=None,
             loader=None,
             **kwargs):
    '''
    
    '''
    mem = int(mem) * 1024  # MB
    context = {
        'hypervisor': hypervisor,
        'name': name,
        'cpu': six.text_type(cpu),
        'mem': six.text_type(mem),
    }
    if hypervisor in ['qemu', 'kvm']:
        context['controller_model'] = False
    elif hypervisor == 'vmware':
        # TODO: make bus and model parameterized, this works for 64-bit Linux
        context['controller_model'] = 'lsilogic'

    # By default, set the graphics to listen to all addresses
    if graphics:
        if 'listen' not in graphics:
            graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'}
        elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address':
            graphics['listen']['address'] = '0.0.0.0'

        # Graphics of type 'none' means no graphics device at all
        if graphics.get('type', 'none') == 'none':
            graphics = None
    context['graphics'] = graphics

    if loader and 'path' not in loader:
        log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration')
        loader = None
    elif loader:
        loader_attributes = []
        for key, val in loader.items():
            if key == 'path':
                continue
            loader_attributes.append("{key}='{val}'".format(key=key, val=val))
        loader['_attributes'] = ' '.join(loader_attributes)

    if 'boot_dev' in kwargs:
        context['boot_dev'] = []
        for dev in kwargs['boot_dev'].split():
            context['boot_dev'].append(dev)
    else:
        context['boot_dev'] = ['hd']

    context['loader'] = loader

    if os_type == 'xen':
        # Compute the Xen PV boot method
        if __grains__['os_family'] == 'Suse':
            context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen'
            context['boot_dev'] = []

    if 'serial_type' in kwargs:
        context['serial_type'] = kwargs['serial_type']
    if 'serial_type' in context and context['serial_type'] == 'tcp':
        if 'telnet_port' in kwargs:
            context['telnet_port'] = kwargs['telnet_port']
        else:
            context['telnet_port'] = 23023  # FIXME: use random unused port
    if 'serial_type' in context:
        if 'console' in kwargs:
            context['console'] = kwargs['console']
        else:
            context['console'] = True

    context['disks'] = []
    disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'}
    for i, disk in enumerate(diskp):
        prefix = disk_bus_map.get(disk['model'], 'sd')
        disk_context = {
            'device': disk.get('device', 'disk'),
            'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]),
            'disk_bus': disk['model'],
            'type': disk['format'],
            'index': six.text_type(i),
        }
        if 'source_file' and disk['source_file']:
            disk_context['source_file'] = disk['source_file']

        if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']:
            disk_context['address'] = False
            disk_context['driver'] = True
        elif hypervisor in ['esxi', 'vmware']:
            disk_context['address'] = True
            disk_context['driver'] = False
        context['disks'].append(disk_context)
    context['nics'] = nicp

    context['os_type'] = os_type
    context['arch'] = arch

    fn_ = 'libvirt_domain.jinja'
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template %s', fn_)
        return ''

    return template.render(**context)
250480
def render_xml(result, cfg, **kwargs):
    
    # Raw mode
    if cfg.dis == 'raw':
        return {'data': {'text/plain': result.decode('utf-8')},
                'metadata': {}}
    # Table
    try:
        import xml.etree.cElementTree as ET
    except ImportError:
        import xml.etree.ElementTree as ET
    root = ET.fromstring(result)
    try:
        ns = {'ns': re.match(r'\{([^}]+)\}', root.tag).group(1)}
    except Exception:
        raise KrnlException('Invalid XML data: cannot get namespace')
    columns = [c.attrib['name'] for c in root.find('ns:head', ns)]
    results = root.find('ns:results', ns)
    nrow = len(results)
    j = xml_iterator(columns, results, set(cfg.lan), add_vtype=cfg.typ)
    n, data = html_table(j, limit=cfg.lmt, withtype=cfg.typ)
    data += div('Total: {}, Shown: {}', nrow, n, css="tinfo")
    return {'data': {'text/html': div(data)},
            'metadata': {}}
999691
def toxml(self):
        

        return '<Constant' +\
          (' name = "{0}"'.format(self.name) if self.name else '') +\
          (' symbol = "{0}"'.format(self.symbol) if self.symbol else '') +\
          (' value = "{0}"'.format(self.value) if self.value else '') +\
          (' dimension = "{0}"'.format(self.dimension) if self.dimension else '') +\
          (' description = "{0}"'.format(self.description) if self.description else '') +\
          '/>'
591296
private static void generateParseOnXmlAttributes(BindTypeContext context, MethodSpec.Builder methodBuilder,
			BindEntity entity) {
		BindTransform bindTransform;

		int count = 0;
		// count property to manage
		{
			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.ATTRIBUTE)
					continue;

				count++;
			}
		}

		if (count > 0) {
			// @formatter:off
			methodBuilder.addCode("\n// attributes \n");
			methodBuilder.addStatement("String attributeName = null");
			// methodBuilder.addStatement("String attributeValue = null");

			methodBuilder.addStatement("int attributesCount = xmlParser.getAttributeCount();");
			methodBuilder.beginControlFlow(
					"for (int attributeIndex = 0; attributeIndex < attributesCount; attributeIndex++)");
			methodBuilder.addStatement("attributeName = xmlParser.getAttributeName(attributeIndex)");
			// methodBuilder.addStatement("attributeValue =
			// $T.unescapeXml(xmlParser.getAttributeValue(attributeIndex))",
			// StringEscapeUtils.class);
			methodBuilder.beginControlFlow("switch(attributeName)$>");

			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.ATTRIBUTE)
					continue;

				methodBuilder.addCode("case $S:\n$>", BindProperty.xmlName(property));

				bindTransform = BindTransformer.lookup(property);
				methodBuilder.addCode("// field $L (mapped by $S)\n", property.getName(),
						BindProperty.xmlName(property));
				bindTransform.generateParseOnXml(context, methodBuilder, "xmlParser",
						property.getPropertyType().getTypeName(), "instance", property);

				methodBuilder.addStatement("$<break");
			}

			methodBuilder.addCode("default:\n$>");
			methodBuilder.addStatement("$<break$<");
			methodBuilder.endControlFlow();

			methodBuilder.endControlFlow();
			// @formatter:on
		} else {
			methodBuilder.addCode("// No attributes found\n");
		}
	}
867045
def generate(basename, xml):
    ''''''

    if basename.endswith('.js'):
        filename = basename
    else:
        filename = basename + '.js'

    msgs = []
    enums = []
    filelist = []
    for x in xml:
        msgs.extend(x.message)
        enums.extend(x.enum)
        filelist.append(os.path.basename(x.filename))

    for m in msgs:
        if xml[0].little_endian:
            m.fmtstr = '<'
        else:
            m.fmtstr = '>'
        for f in m.ordered_fields:
            m.fmtstr += mavfmt(f)
        m.order_map = [ 0 ] * len(m.fieldnames)
        for i in range(0, len(m.fieldnames)):
            m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i])

    print("Generating %s" % filename)
    outf = open(filename, "w")
    generate_preamble(outf, msgs, filelist, xml[0])
    generate_enums(outf, enums)
    generate_message_ids(outf, msgs)
    generate_classes(outf, msgs)
    generate_mavlink_class(outf, msgs, xml[0])
    generate_footer(outf)
    outf.close()
    print("Generated %s OK" % filename)
1292799
private static void generateParserOnXmlCharacters(BindTypeContext context, MethodSpec.Builder methodBuilder,
			String instanceName, String parserName, BindEntity entity) {
		BindTransform bindTransform;
		int count = 0;
		for (BindProperty property : entity.getCollection()) {
			if (property.xmlInfo.xmlType != XmlType.VALUE && property.xmlInfo.xmlType != XmlType.VALUE_CDATA)
				continue;

			count++;
			methodBuilder.beginControlFlow("if (elementName!=null && $L.hasText())", parserName);
			methodBuilder.addCode("// property $L\n", property.getName());
			bindTransform = BindTransformer.lookup(property);
			bindTransform.generateParseOnXml(context, methodBuilder, parserName,
					property.getPropertyType().getTypeName(), "instance", property);
			methodBuilder.endControlFlow();
		}

		if (count == 0) {
			methodBuilder.addCode("// no property is binded to VALUE o CDATA ");
		}
	}
48872
def generate_xml
      values = { 
        'charset' => @options.charset,
        'files'   => gen_into(@files),
        'classes' => gen_into(@classes),
        'title'        => CGI.escapeHTML(@options.title),
      }
      
      # this method is defined in the template file
      write_extra_pages if defined? write_extra_pages

      template = TemplatePage.new(RDoc::Page::ONE_PAGE)

      if @options.op_name
        opfile = File.open(@options.op_name, "w")
      else
        opfile = $stdout
      end
      template.write_html_on(opfile, values)
    end
1333557
private XmlHttpResponse getReportXml(String reportXmlFilename) {
        String url = LalCallColumnFixture.getLalUrl() + "/xmlrr/archive/Report/" + reportXmlFilename;
        return env.doHttpGetXml(url);
    }
684357
def generate(self, *args, **kwargs):
        
        xmlstr = str(self)
        filename = args[0]
        with open(filename, 'w') as fil:
            fil.write(xmlstr)

        with open(self.get_latest_filename('junit.xml'), "w") as latest_report:
            latest_report.write(xmlstr)
448810
def generate_report(report_id, wait = false)
      xml = make_xml('ReportGenerateRequest', { 'report-id' => report_id })
      response = execute(xml)
      if response.success
        response.res.elements.each('//ReportSummary') do |summary|
          summary = ReportSummary.parse(summary)
          # If not waiting or the report is finished, return now.
          return summary unless wait && summary.status == 'Started'
        end
      end
      so_far = 0
      while wait
        summary = last_report(report_id)
        return summary unless summary.status == 'Started'
        sleep 5
        so_far += 5
        if (so_far % 60).zero?
          puts "Still waiting. Current status: #{summary.status}"
        end
      end
      nil
    end
539481
void generateRaXml(Definition def, String outputDir)
   {
      if (!def.isUseAnnotation())
      {
         try
         {
            outputDir = outputDir + File.separatorChar + "src" + File.separatorChar +
                  "main" + File.separatorChar + "resources";
            FileWriter rafw = Utils.createFile("ra.xml", outputDir + File.separatorChar + "META-INF");
            RaXmlGen raGen = getRaXmlGen(def);
            raGen.generate(def, rafw);
            rafw.close();
         }
         catch (IOException ioe)
         {
            ioe.printStackTrace();
         }
      }
   }
1007951
private static void generateParserOnXmlStartElement(BindTypeContext context, MethodSpec.Builder methodBuilder,
			String instanceName, String parserName, BindEntity entity) {
		BindTransform bindTransform;
		// start and inner bean
		methodBuilder.addStatement("currentTag = xmlParser.getName().toString()");

		int count = 0;
		// count property to manage
		{
			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.TAG)
					continue;

				bindTransform = BindTransformer.lookup(property);

				// here we manage only property of bean type
				if (bindTransform != null) {
					count++;
				}
			}
		}

		if (count > 0) {
			// switch for tag elements
			// @formatter:off
			methodBuilder.beginControlFlow("switch(currentTag)$>");

			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.TAG)
					continue;

				bindTransform = BindTransformer.lookup(property);

				// here we manage only property of bean type
				if (bindTransform != null) {
					methodBuilder.addCode("case $S:\n$>", BindProperty.xmlName(property));
					methodBuilder.addCode("// property $L (mapped on $S)\n", property.getName(),
							BindProperty.xmlName(property));

					// methodBuilder.beginControlFlow("if
					// (!xmlParser.isEmptyElement())");
					bindTransform.generateParseOnXml(context, methodBuilder, "xmlParser",
							property.getPropertyType().getTypeName(), "instance", property);
					// methodBuilder.endControlFlow();

					methodBuilder.addStatement("$<break");
				}
			}

			methodBuilder.addCode("default:\n$>");
			// methodBuilder.addStatement("$L.skipElement()", parserName);

			methodBuilder.addStatement("$<break");
			methodBuilder.endControlFlow();
		} else {
			methodBuilder.addCode("// No property to manage here\n");
		}
		// @formatter:on

	}
1307519
void generateAntXml(Definition def, String outputDir)
   {
      try
      {
         FileWriter antfw = Utils.createFile("build.xml", outputDir);
         BuildXmlGen bxGen = new BuildXmlGen();
         bxGen.generate(def, antfw);
         antfw.close();
      }
      catch (IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
841639
public void generateReport(List<XmlSuite> xmlSuites,
                               List<ISuite> suites,
                               String outputDirectoryName)
    {
        removeEmptyDirectories(new File(outputDirectoryName));
        
        File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);
        outputDirectory.mkdirs();

        Collection<TestClassResults> flattenedResults = flattenResults(suites);

        for (TestClassResults results : flattenedResults)
        {
            VelocityContext context = createContext();
            context.put(RESULTS_KEY, results);

            try
            {
                generateFile(new File(outputDirectory, results.getTestClass().getName() + '_' + RESULTS_FILE),
                             RESULTS_FILE + TEMPLATE_EXTENSION,
                             context);
            }
            catch (Exception ex)
            {
                throw new ReportNGException("Failed generating JUnit XML report.", ex);
            }
        }
    }
1363815
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
        
        nl = "\n"
        out = []
        namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
                                                            for v in vlist)
        nextLevelIndent = indent + "  "

        # collapse out indents if formatting is not desired
        if not formatted:
            indent = ""
            nextLevelIndent = ""
            nl = ""

        selfTag = None
        if doctag is not None:
            selfTag = doctag
        else:
            if self.__name:
                selfTag = self.__name

        if not selfTag:
            if namedItemsOnly:
                return ""
            else:
                selfTag = "ITEM"

        out += [ nl, indent, "<", selfTag, ">" ]

        for i,res in enumerate(self.__toklist):
            if isinstance(res,ParseResults):
                if i in namedItems:
                    out += [ res.asXML(namedItems[i],
                                        namedItemsOnly and doctag is None,
                                        nextLevelIndent,
                                        formatted)]
                else:
                    out += [ res.asXML(None,
                                        namedItemsOnly and doctag is None,
                                        nextLevelIndent,
                                        formatted)]
            else:
                # individual token, see if there is a name for it
                resTag = None
                if i in namedItems:
                    resTag = namedItems[i]
                if not resTag:
                    if namedItemsOnly:
                        continue
                    else:
                        resTag = "ITEM"
                xmlBodyText = _xml_escape(_ustr(res))
                out += [ nl, nextLevelIndent, "<", resTag, ">",
                                                xmlBodyText,
                                                "</", resTag, ">" ]

        out += [ nl, indent, "</", selfTag, ">" ]
        return "".join(out)