Take a Django node object from our CODA store and make an XML
    representation
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
1014046
def serialize(self, queryset, **options):
        
        self.options = options

        self.stream = options.get("stream", StringIO())
        self.selected_fields = options.get("fields")
        self.use_natural_keys = options.get("use_natural_keys", True)
        
        self.xml = options.get("xml", None)
        self.root = (self.xml == None)
        
        self.start_serialization()
        for obj in queryset:
            # hook for having custom serialization
            if hasattr(obj, '__serialize__'):
                obj.__serialize__(self.xml)
            else:
                self.serialize_object(obj)
        self.end_serialization()
        return self.getvalue()
1127169
def _node_to_model(tree_or_item, package, parent=None,
                   lucent_id=TRANSLUCENT_BINDER_ID):
    """"""
    if 'contents' in tree_or_item:
        # It is a binder.
        tree = tree_or_item
        # Grab the package metadata, so we have required license info
        metadata = package.metadata.copy()
        if tree['id'] == lucent_id:
            metadata['title'] = tree['title']
            binder = TranslucentBinder(metadata=metadata)
        else:
            try:
                package_item = package.grab_by_name(tree['id'])
                binder = BinderItem(package_item, package)
            except KeyError:  # Translucent w/ id
                metadata.update({
                   'title': tree['title'],
                   'cnx-archive-uri': tree['id'],
                   'cnx-archive-shortid': tree['shortId']})
                binder = Binder(tree['id'], metadata=metadata)
        for item in tree['contents']:
            node = _node_to_model(item, package, parent=binder,
                                  lucent_id=lucent_id)
            if node.metadata['title'] != item['title']:
                binder.set_title_for_node(node, item['title'])
        result = binder
    else:
        # It is a document.
        item = tree_or_item
        package_item = package.grab_by_name(item['id'])
        result = adapt_item(package_item, package)
    if parent is not None:
        parent.append(result)
    return result
1160646
def to_xml(self):
        '''
        
        '''
        for n, v in {"name": self.name, "quantity": self.quantity,
                     "unit_price": self.unit_price}.items():
            if is_empty_or_none(v):
                raise LineError("'%s' attribute cannot be empty or None." %
                                    n)

        doc = Document()
        root = doc.createElement("line")
        super(Line, self).to_xml(root)
        self._create_text_node(root, "date", self.date)
        self._create_text_node(root, "name", self.name, True)
        self._create_text_node(root, "description", self.description, True)
        self._create_text_node(root, "quantity", self.quantity)
        self._create_text_node(root, "unitPrice", self.unit_price)
        self._create_text_node(root, "unit", self.unit)
        self._create_text_node(root, "gin", self.gin)
        self._create_text_node(root, "gtin", self.gtin)
        self._create_text_node(root, "sscc", self.sscc)

        if len(self.__discounts):
            discounts = root.ownerDocument.createElement("discounts")
            root.appendChild(discounts)
            for discount in self.__discounts:
                if not issubclass(discount.__class__, Discount):
                    raise LineError('discount of type %s is not an ' \
                                    'instance or a subclass of %s' %
                                    (discount.__class__.__name__,
                                     Discount.__name__))
                discounts.appendChild(discount.to_xml())

        if len(self.__taxes):
            taxes = root.ownerDocument.createElement("taxes")
            root.appendChild(taxes)
            for tax in self.__taxes:
                if not issubclass(tax.__class__, Tax):
                    raise LineError('tax of type %s is not an instance ' \
                                        'or a subclass of %s' %
                                        (tax.__class__.__name__, Tax.__name__))
                taxes.appendChild(tax.to_xml())

        return root
53971
def parse_xml(self, node):
        
        import struct
        import array

        self._set_properties(node)
        data = None
        next_gid = None
        data_node = node.find('data')

        encoding = data_node.get('encoding', None)
        if encoding == 'base64':
            from base64 import b64decode

            data = b64decode(data_node.text.strip())

        elif encoding == 'csv':
            next_gid = map(int, "".join(
                line.strip() for line in data_node.text.strip()).split(","))

        elif encoding:
            msg = 'TMX encoding type: {0} is not supported.'
            logger.error(msg.format(encoding))
            raise Exception

        compression = data_node.get('compression', None)
        if compression == 'gzip':
            import gzip

            with gzip.GzipFile(fileobj=six.BytesIO(data)) as fh:
                data = fh.read()

        elif compression == 'zlib':
            import zlib

            data = zlib.decompress(data)

        elif compression:
            msg = 'TMX compression type: {0} is not supported.'
            logger.error(msg.format(compression))
            raise Exception

        # if data is None, then it was not decoded or decompressed, so
        # we assume here that it is going to be a bunch of tile elements
        # TODO: this will/should raise an exception if there are no tiles
        if encoding == next_gid is None:
            def get_children(parent):
                for child in parent.findall('tile'):
                    yield int(child.get('gid'))

            next_gid = get_children(data_node)

        elif data:
            if type(data) == bytes:
                fmt = struct.Struct('<L')
                iterator = (data[i:i + 4] for i in range(0, len(data), 4))
                next_gid = (fmt.unpack(i)[0] for i in iterator)
            else:
                msg = 'layer data not in expected format ({})'
                logger.error(msg.format(type(data)))
                raise Exception

        init = lambda: [0] * self.width
        reg = self.parent.register_gid

        # H (16-bit) may be a limitation for very detailed maps
        self.data = tuple(array.array('H', init()) for i in range(self.height))
        for (y, x) in product(range(self.height), range(self.width)):
            self.data[y][x] = reg(*decode_gid(next(next_gid)))

        return self
118290
def xml2object(self, content):
        
        """
        content = self.xml_filter(content)
        element = ET.fromstring(content)
        tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
        if not self.__options['strip_root']:
            node = self.get_node(element)
            if not self.__options['strip_attr']:
                tree['attrs'] = node['attr']
            return {node['tag']: tree}
        return tree
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
855950
def _gen_pool_xml(name,
                  ptype,
                  target=None,
                  permissions=None,
                  source_devices=None,
                  source_dir=None,
                  source_adapter=None,
                  source_hosts=None,
                  source_auth=None,
                  source_name=None,
                  source_format=None):
    '''
    
    '''
    hosts = [host.split(':') for host in source_hosts or []]
    context = {
        'name': name,
        'ptype': ptype,
        'target': {'path': target, 'permissions': permissions},
        'source': {
            'devices': source_devices or [],
            'dir': source_dir,
            'adapter': source_adapter,
            'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts],
            'auth': source_auth,
            'name': source_name,
            'format': source_format
        }
    }
    fn_ = 'libvirt_pool.jinja'
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template %s', fn_)
        return ''
    return template.render(**context)
96253
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        if node.tag.lower() != 'meta':
            raise Exception("Expected meta tag but got '" + node.tag + "' instead")

        key = node.attrib['id']
        if node.text:
            value = node.text
        else:
            value = None
        operator = 'set'
        if 'operator' in node.attrib:
            operator= node.attrib['operator']
        if operator == 'set':
            cls = SetMetaField
        elif operator == 'unset':
            cls = UnsetMetaField
        elif operator == 'copy':
            cls = CopyMetaField
        elif operator == 'parameter':
            cls = ParameterMetaField
        return cls(key, value)
1228289
def to_xml(node, pretty=False):
    
    fout = Sio()
    etree = et.ElementTree(node)

    etree.write(fout)
    xml = fout.getvalue()
    if pretty:
        xml = pretty_xml(xml, True)
    return xml
917284
def to_xml(self):
        
        type_converter = _get_encoder_method(self._data_type)
        # Convert from python native to device cloud
        encoded_data = type_converter(self._data)

        out = StringIO()
        out.write("<DataPoint>")
        out.write("<streamId>{}</streamId>".format(self.get_stream_id()))
        out.write("<data>{}</data>".format(encoded_data))
        conditional_write(out, "<description>{}</description>", self.get_description())
        if self.get_timestamp() is not None:
            out.write("<timestamp>{}</timestamp>".format(isoformat(self.get_timestamp())))
        conditional_write(out, "<quality>{}</quality>", self.get_quality())
        if self.get_location() is not None:
            out.write("<location>%s</location>" % ",".join(map(str, self.get_location())))
        conditional_write(out, "<streamType>{}</streamType>", self.get_data_type())
        conditional_write(out, "<streamUnits>{}</streamUnits>", self.get_units())
        out.write("</DataPoint>")
        return out.getvalue()
590025
def XML(uri, tc, ps, **keywords):
    '''
    '''
    source = urllib.urlopen(uri, **keywords)
    enc = source.info().getencoding()
    if enc in ['7bit', '8bit', 'binary']:
        data = source
    else:
        data = StringIO.StringIO()
        mimetools.decode(source, data, enc)
        data.seek(0)
    dom = ps.readerclass().fromStream(data)
    return _child_elements(dom)[0]
1068628
def LoadFromXml(self, node, handle):
		
		from Ucs import ClassFactory

		self.SetHandle(handle)
		if node.hasAttributes():
			# attributes = node._get_attributes()
			# attCount = attributes._get_length()
			attributes = node.attributes
			attCount = len(attributes)
			for i in range(attCount):
				attNode = attributes.item(i)
				# attr = UcsUtils.WordU(attNode._get_name())
				attr = UcsUtils.WordU(attNode.localName)
				if (attr in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId)):
					atMeta = UcsUtils.GetUcsMethodMeta(self.classId, attr)
					if ((atMeta.io == "Input") or (atMeta.isComplexType)):
						continue
					# self.setattr(attr, str(attNode.nodeValue))
					self.setattr(attr, str(attNode.value))
				# elif (attNode._get_name() in externalMethodAttrs):
				#	self.setattr(attNode._get_name(), str(attNode.nodeValue))
				elif (attNode.localName in externalMethodAttrs):
					self.setattr(attNode.localName, str(attNode.value))

		if (node.hasChildNodes()):
			# childList = node._get_childNodes()
			# childCount = childList._get_length()
			childList = node.childNodes
			childCount = len(childList)
			for i in range(childCount):
				childNode = childList.item(i)
				if (childNode.nodeType != Node.ELEMENT_NODE):
					continue

				cln = UcsUtils.WordU(childNode.localName)
				if cln in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId):
					atMeta = UcsUtils.GetUcsMethodMeta(self.classId, cln)
					if ((atMeta.io == "Output") and (atMeta.isComplexType)):
						c = ClassFactory(atMeta.fieldType)
						if (c != None):
							self.setattr(cln, c)
							c.LoadFromXml(childNode, handle)
585537
def xml(self, attribs = None,elements = None, skipchildren = False):
        """"""
        attribs = {}
        if not self.offset is None:
            attribs['{' + NSFOLIA + '}offset'] = str(self.offset)
        if self.parent and self.ref:
            attribs['{' + NSFOLIA + '}ref'] = self.ref

        #if self.cls != 'current' and not (self.cls == 'original' and any( isinstance(x, Original) for x in self.ancestors() )  ):
        #    attribs['{' + NSFOLIA + '}class'] = self.cls
        #else:
        #    if '{' + NSFOLIA + '}class' in attribs:
        #        del attribs['{' + NSFOLIA + '}class']
        #return E.t(self.value, **attribs)

        e = super(TextContent,self).xml(attribs,elements,skipchildren)
        if '{' + NSFOLIA + '}class' in e.attrib and e.attrib['{' + NSFOLIA + '}class'] == "current":
            #delete 'class=current'
            del e.attrib['{' + NSFOLIA + '}class']

        return e
764463
def from_string(cls, jss, xml_string):
        
        root = ElementTree.fromstring(xml_string.encode('utf-8'))
        return cls(jss, root)
1243948
def to_xml(self, root):
        '''
        
        '''
        if not len(self.__custom_elements):
            return

        for uri, tags in self.__custom_elements.items():
            prefix, url = uri.split(":", 1)
            for name, value in tags.items():
                self.__createElementNS(root, url, prefix + ":" + name, value)

        return root
488385
def nodes_to_object(self, node, object):
        ""

        for n in list(node):
            self.node_to_object(n, object)