Ingest xml to create a citation

        :param resource: XML on which to do xpath
        :param element: Element where the citation should be stored
        :param xpath: XPath to use to retrieve citation

        :return: XmlCtsCitation
175238
def ingest(cls, resource, element=None, xpath="ti:citation"):
        
        # Reuse of of find citation
        results = resource.xpath(xpath, namespaces=XPATH_NAMESPACES)
        if len(results) > 0:
            citation = cls(
                name=results[0].get("label"),
                xpath=results[0].get("xpath"),
                scope=results[0].get("scope")
            )

            if isinstance(element, cls):
                element.child = citation
                cls.ingest(
                    resource=results[0],
                    element=element.child
                )
            else:
                element = citation
                cls.ingest(
                    resource=results[0],
                    element=element
                )

            return citation

        return None
315909
def resource_etree_element(self, resource, element_name='url'):
        
        e = Element(element_name)
        sub = Element('loc')
        sub.text = resource.uri
        e.append(sub)
        if (resource.timestamp is not None):
            # Create appriate element for timestamp
            sub = Element('lastmod')
            sub.text = str(resource.lastmod)  # W3C Datetime in UTC
            e.append(sub)
        md_atts = {}
        for att in ('capability', 'change', 'hash', 'length', 'path', 'mime_type',
                    'md_at', 'md_completed', 'md_from', 'md_until'):
            val = getattr(resource, att, None)
            if (val is not None):
                md_atts[self._xml_att_name(att)] = str(val)
        if (len(md_atts) > 0):
            md = Element('rs:md', md_atts)
            e.append(md)
        # add any <rs:ln>
        if (hasattr(resource, 'ln') and
                resource.ln is not None):
            for ln in resource.ln:
                self.add_element_with_atts_to_etree(e, 'rs:ln', ln)
        if (self.pretty_xml):
            e.tail = "\n"
        return(e)
731249
def construct_xml_tree(self):
        """"""
        report = et.Element('report')
        plipversion = et.SubElement(report, 'plipversion')
        plipversion.text = __version__
        date_of_creation = et.SubElement(report, 'date_of_creation')
        date_of_creation.text = time.strftime("%Y/%m/%d")
        citation_information = et.SubElement(report, 'citation_information')
        citation_information.text = "Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler. " \
            "Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315"
        mode = et.SubElement(report, 'mode')
        if config.DNARECEPTOR:
            mode.text = 'dna_receptor'
        else:
            mode.text = 'default'
        pdbid = et.SubElement(report, 'pdbid')
        pdbid.text = self.mol.pymol_name.upper()
        filetype = et.SubElement(report, 'filetype')
        filetype.text = self.mol.filetype.upper()
        pdbfile = et.SubElement(report, 'pdbfile')
        pdbfile.text = self.mol.sourcefiles['pdbcomplex']
        pdbfixes = et.SubElement(report, 'pdbfixes')
        pdbfixes.text = str(self.mol.information['pdbfixes'])
        filename = et.SubElement(report, 'filename')
        filename.text = str(self.mol.sourcefiles.get('filename') or None)
        exligs = et.SubElement(report, 'excluded_ligands')
        for i, exlig in enumerate(self.excluded):
            e = et.SubElement(exligs, 'excluded_ligand', id=str(i + 1))
            e.text = exlig
        covalent = et.SubElement(report, 'covlinkages')
        for i, covlinkage in enumerate(self.mol.covalent):
            e = et.SubElement(covalent, 'covlinkage', id=str(i + 1))
            f1 = et.SubElement(e, 'res1')
            f2 = et.SubElement(e, 'res2')
            f1.text = ":".join([covlinkage.id1, covlinkage.chain1, str(covlinkage.pos1)])
            f2.text = ":".join([covlinkage.id2, covlinkage.chain2, str(covlinkage.pos2)])
        return report
216692
public static void writeResources(Element node, XMLResources resources, XMLBuilder builder) {
		if (resources != null) {
			final Element resourcesNode = builder.createElement(NODE_RESOURCES);
			for (final java.util.Map.Entry<Long, Entry> pair : resources.getPairs().entrySet()) {
				final Entry e = pair.getValue();
				if (e.isURL()) {
					final Element resourceNode = builder.createElement(NODE_RESOURCE);
					resourceNode.setAttribute(ATTR_ID, XMLResources.getStringIdentifier(pair.getKey()));
					resourceNode.setAttribute(ATTR_URL, e.getURL().toExternalForm());
					resourceNode.setAttribute(ATTR_MIMETYPE, e.getMimeType());
					resourcesNode.appendChild(resourceNode);
				} else if (e.isFile()) {
					final Element resourceNode = builder.createElement(NODE_RESOURCE);
					resourceNode.setAttribute(ATTR_ID, XMLResources.getStringIdentifier(pair.getKey()));
					final File file = e.getFile();
					final StringBuilder url = new StringBuilder();
					url.append("file:"); //$NON-NLS-1$
					boolean addSlash = false;
					for (final String elt : FileSystem.split(file)) {
						try {
							if (addSlash) {
								url.append("/"); //$NON-NLS-1$
							}
							url.append(URLEncoder.encode(elt, Charset.defaultCharset().name()));
						} catch (UnsupportedEncodingException e1) {
							throw new Error(e1);
						}
						addSlash = true;
					}
					resourceNode.setAttribute(ATTR_FILE, url.toString());
					resourceNode.setAttribute(ATTR_MIMETYPE, e.getMimeType());
					resourcesNode.appendChild(resourceNode);
				} else if (e.isEmbeddedData()) {
					final Element resourceNode = builder.createElement(NODE_RESOURCE);
					resourceNode.setAttribute(ATTR_ID, XMLResources.getStringIdentifier(pair.getKey()));
					resourceNode.setAttribute(ATTR_MIMETYPE, e.getMimeType());
					final byte[] data = e.getEmbeddedData();
					final CDATASection cdata = builder.createCDATASection(toString(data));
					resourceNode.appendChild(cdata);
					resourcesNode.appendChild(resourceNode);
				}
			}
			if (resourcesNode.getChildNodes().getLength() > 0) {
				node.appendChild(resourcesNode);
			}
		}
	}
849140
def serialize_for_reading(element):
    
    xml = etree.tostring(element, encoding='unicode', pretty_print=True)
    return XmlString(xml)
1177198
def data(self, root, preserve_root=False):
        ''''''
        # If preserve_root is False, return the root element. This is easiest
        # done by wrapping the XML in a dummy root element that will be ignored.
        if preserve_root:
            new_root = root.makeelement('dummy_root', {})
            new_root.insert(0, root)
            root = new_root

        # If no children, just return the text
        children = [node for node in root if isinstance(node.tag, basestring)]
        if len(children) == 0:
            return self._fromstring(root.text)

        # Element names become object properties
        count = Counter(child.tag for child in children)
        result = self.dict()
        for child in children:
            if count[child.tag] == 1:
                result[child.tag] = self.data(child)
            else:
                result.setdefault(child.tag, self.list()).append(self.data(child))

        return result
607439
def xml(self, attribs = None,elements = None, skipchildren = False):
        
        E = ElementMaker(namespace=NSFOLIA,nsmap={None: NSFOLIA, 'xml' : "http://www.w3.org/XML/1998/namespace"})

        if not attribs: attribs = {}
        if not elements: elements = []

        if self.id:
            attribs['{http://www.w3.org/XML/1998/namespace}id'] = self.id

        #Some attributes only need to be added if they are not the same as what's already set in the declaration
        if not isinstance(self, AbstractAnnotationLayer):
            if '{' + NSFOLIA + '}set' not in attribs: #do not override if overloaded function already set it
                try:
                    if self.set:
                        if not self.ANNOTATIONTYPE in self.doc.annotationdefaults or len(self.doc.annotationdefaults[self.ANNOTATIONTYPE]) != 1 or list(self.doc.annotationdefaults[self.ANNOTATIONTYPE].keys())[0] != self.set:
                            if self.set != None:
                                if self.ANNOTATIONTYPE in self.doc.set_alias and self.set in self.doc.set_alias[self.ANNOTATIONTYPE]:
                                    attribs['{' + NSFOLIA + '}set'] = self.doc.set_alias[self.ANNOTATIONTYPE][self.set] #use alias instead
                                else:
                                    attribs['{' + NSFOLIA + '}set'] = self.set
                except AttributeError:
                    pass

        if '{' + NSFOLIA + '}class' not in attribs: #do not override if caller already set it
            try:
                if self.cls:
                    attribs['{' + NSFOLIA + '}class'] = self.cls
            except AttributeError:
                pass

        if '{' + NSFOLIA + '}annotator' not in attribs: #do not override if caller already set it
            try:
                if self.annotator and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ( 'annotator' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.annotator != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['annotator'])):
                    attribs['{' + NSFOLIA + '}annotator'] = self.annotator
                if self.annotatortype and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ('annotatortype' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.annotatortype != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['annotatortype'])):
                    if self.annotatortype == AnnotatorType.AUTO:
                        attribs['{' + NSFOLIA + '}annotatortype'] = 'auto'
                    elif self.annotatortype == AnnotatorType.MANUAL:
                        attribs['{' + NSFOLIA + '}annotatortype'] = 'manual'
            except AttributeError:
                pass

        if '{' + NSFOLIA + '}confidence' not in attribs: #do not override if caller already set it
            if self.confidence:
                attribs['{' + NSFOLIA + '}confidence'] = str(self.confidence)

        if '{' + NSFOLIA + '}n' not in attribs: #do not override if caller already set it
            if self.n:
                attribs['{' + NSFOLIA + '}n'] = str(self.n)

        if '{' + NSFOLIA + '}auth' not in attribs: #do not override if caller already set it
            try:
                if not self.AUTH or not self.auth: #(former is static, latter isn't)
                    attribs['{' + NSFOLIA + '}auth'] = 'no'
            except AttributeError:
                pass

        if '{' + NSFOLIA + '}datetime' not in attribs: #do not override if caller already set it
            if self.datetime and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ( 'datetime' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.datetime != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['datetime'])):
                attribs['{' + NSFOLIA + '}datetime'] = self.datetime.strftime("%Y-%m-%dT%H:%M:%S")

        if '{' + NSFOLIA + '}src' not in attribs: #do not override if caller already set it
            if self.src:
                attribs['{' + NSFOLIA + '}src'] = self.src

        if '{' + NSFOLIA + '}speaker' not in attribs: #do not override if caller already set it
            if self.speaker:
                attribs['{' + NSFOLIA + '}speaker'] = self.speaker

        if '{' + NSFOLIA + '}begintime' not in attribs: #do not override if caller already set it
            if self.begintime:
                attribs['{' + NSFOLIA + '}begintime'] = "%02d:%02d:%02d.%03d" % self.begintime

        if '{' + NSFOLIA + '}endtime' not in attribs: #do not override if caller already set it
            if self.endtime:
                attribs['{' + NSFOLIA + '}endtime'] = "%02d:%02d:%02d.%03d" % self.endtime

        if '{' + NSFOLIA + '}textclass' not in attribs: #do not override if caller already set it
            if self.textclass and self.textclass != "current":
                attribs['{' + NSFOLIA + '}textclass'] = self.textclass

        if '{' + NSFOLIA + '}metadata' not in attribs: #do not override if caller already set it
            if self.metadata:
                attribs['{' + NSFOLIA + '}metadata'] = self.metadata

        if self.XLINK:
            if self.href:
                attribs['{http://www.w3.org/1999/xlink}href'] = self.href
                if not self.xlinktype:
                    attribs['{http://www.w3.org/1999/xlink}type'] = "simple"
            if self.xlinktype:
                attribs['{http://www.w3.org/1999/xlink}type'] = self.xlinktype
            if self.xlinklabel:
                attribs['{http://www.w3.org/1999/xlink}label'] = self.xlinklabel
            if self.xlinkrole:
                attribs['{http://www.w3.org/1999/xlink}role'] = self.xlinkrole
            if self.xlinkshow:
                attribs['{http://www.w3.org/1999/xlink}show'] = self.xlinkshow
            if self.xlinktitle:
                attribs['{http://www.w3.org/1999/xlink}title'] = self.xlinktitle

        omitchildren =  []

        #Are there predetermined Features in ACCEPTED_DATA?
        for c in self.ACCEPTED_DATA:
            if issubclass(c, Feature) and c.SUBSET:
                #Do we have any of those?
                for c2 in self.data:
                    if c2.__class__ is c and c.SUBSET == c2.SUBSET and c2.cls:
                        #Yes, serialize them as attributes
                        attribs[c2.SUBSET] = c2.cls
                        omitchildren.append(c2) #and skip them as elements
                        break #only one

        e  = makeelement(E, '{' + NSFOLIA + '}' + self.XMLTAG, **attribs)



        if not skipchildren and self.data:
            #append children,
            # we want make sure that text elements are in the right order, 'current' class first
            # so we first put them in  a list
            textelements = []
            otherelements = []
            for child in self:
                if isinstance(child, TextContent):
                    if child.cls == 'current':
                        textelements.insert(0, child)
                    else:
                        textelements.append(child)
                elif not child in omitchildren:
                    otherelements.append(child)
            for child in textelements+otherelements:
                if (self.TEXTCONTAINER or self.PHONCONTAINER) and isstring(child):
                    if len(e) == 0:
                        if e.text:
                            e.text += child
                        else:
                            e.text = child
                    else:
                        #add to tail of last child
                        if e[-1].tail:
                            e[-1].tail += child
                        else:
                            e[-1].tail = child

                else:
                    xml = child.xml() #may return None in rare occassions, meaning we wan to skip
                    if not xml is None:
                        e.append(xml)

        if elements: #extra elements
            for e2 in elements:
                if isinstance(e2, str) or (sys.version < '3' and isinstance(e2, unicode)):
                    if e.text is None:
                        e.text = e2
                    else:
                        e.text += e2
                else:
                    e.append(e2)
        return e
1119882
def _findCRefPattern(self, xml):
        
        if not self.citation.is_set():
            citation = xml.xpath("//tei:refsDecl[@n='CTS']", namespaces=XPATH_NAMESPACES)
            if len(citation):
                self.citation = Citation.ingest(resource=citation[0], xpath=".//tei:cRefPattern")
            else:
                raise MissingRefsDecl("No reference declaration (refsDecl) found.")
649644
def create_element(tag: str, name: str = None, base: type = None,
                   attr: dict = None) -> Node:
    
    from wdom.web_node import WdomElement
    from wdom.tag import Tag
    from wdom.window import customElements
    if attr is None:
        attr = {}
    if name:
        base_class = customElements.get((name, tag))
    else:
        base_class = customElements.get((tag, None))
    if base_class is None:
        attr['_registered'] = False
        base_class = base or WdomElement
    if issubclass(base_class, Tag):
        return base_class(**attr)
    return base_class(tag, **attr)
193085
def nodeToXML(nodeObject):
    

    xmlRoot = etree.Element(NODE + "node", nsmap=NODE_NSMAP)
    nameNode = etree.SubElement(xmlRoot, NODE + "name")
    nameNode.text = nodeObject.node_name
    urlNode = etree.SubElement(xmlRoot, NODE + "url")
    urlNode.text = nodeObject.node_url
    pathNode = etree.SubElement(xmlRoot, NODE + "path")
    pathNode.text = nodeObject.node_path
    capNode = etree.SubElement(xmlRoot, NODE + "capacity")
    capNode.text = str(nodeObject.node_capacity)
    sizeNode = etree.SubElement(xmlRoot, NODE + "size")
    sizeNode.text = str(nodeObject.node_size)
    if nodeObject.last_checked:
        checkedNode = etree.SubElement(xmlRoot, NODE + "lastChecked")
        checkedNode.text = nodeObject.last_checked.strftime(TIME_FORMAT_STRING)
    return xmlRoot
1136683
def xpath(self, xpath_str):
        
        return super(BaseOxmlElement, self).xpath(
            xpath_str, namespaces=nsmap
        )
1037045
private static Element getVideoXML(Resource xml) throws IOException, SAXException {
	if (!xml.exists()) {
	    createFileFromResource("/resource/video/video.xml", xml);
	}
	Document doc = loadDocument(xml);
	return doc.getDocumentElement();
    }
1209736
def xml(self):
        

        root = super(ImpactLayerMetadata, self).xml
        provenance_path = self._special_properties['provenance']
        provenance_element = root.find(provenance_path, XML_NS)

        # find the provenance parent tag
        if provenance_element is not None:
            # there is already a provenance tag so we remove it
            provenance_parent = provenance_element.getparent()
            provenance_parent.remove(provenance_element)
        else:
            # find the parent using the provenance path minus one level
            provenance_parent = '/'.join(provenance_path.split('/')[:-1])
            provenance_parent = root.find(provenance_parent, XML_NS)

        # generate the provenance xml element
        provenance_element = ElementTree.fromstring(self.provenance.xml)
        provenance_parent.append(provenance_element)
        return prettify_xml(ElementTree.tostring(root, 'unicode'))
348399
def Element(cls, s, *args):
        """"""
        sargs = []
        for arg in args:
            if type(arg) == etree._Element:
                sargs.append(etree.tounicode(arg))
            else:
                sargs.append(arg)
        if type(s) == etree._Element:
            t = etree.tounicode(s)
        else:
            t = s
        if len(args) == 0:
            return XML.fromstring(t)
        else:
            return XML.fromstring(t % tuple(sargs))
1171526
def _load_xml(self):
        
        if self._xml is not None:
            return
        matcher = "\[(?:Normal|Conditional) Substitution\(index=(\d+), type=\d+\)\]"
        self._xml = re.sub(matcher, "{\\1:}",
                           self._template_node.template_format().replace("{", "{{").replace("}", "}}"))
142718
def resource_from_data(self, data_element, resource=None):
        
        return self._mapping.map_to_resource(data_element, resource=resource)
475533
def getXML(self):
        
        xml='<'+self._elementName+' '
        for key,value in list(self._attributes.items()):
            if value != None:
                xml+=key+'="'+self.quote_attrib(str(value))+'" '
        if  len(self._subElements)==0: #self._textContent==None and
            xml+=' />\n'
        else:
            xml+=' >\n'
            #if self._textContent==None:
            for subelement in self._subElements:
                s = subelement.getXML()
                if type(s) != str:
                    s = str(s)
                xml+=s
               # xml+=str(subelement.getXML())
            #else:
            #if self._textContent!=None:
            #    xml+=self._textContent
            xml+='</'+self._elementName+'>\n'
        #print xml
        return xml