Simple recursive function to build an XML response.
439856
public function _build_xml ($k, $v) {
		if (is_object ($v) && strtolower (get_class ($v)) == 'simplexmlelement') {
			return preg_replace ('/<\?xml(.*?)\?>\n*/', '', $v->asXML ());
		}
		$res = '';
		$attrs = '';
		if (! is_numeric ($k)) {
			$res = '<' . $k . '{{attributes}}>';
		}
		if (is_object ($v)) {
			$v = (array) $v;
		}
		if (is_array ($v)) {
			foreach ($v as $key => $value) {
				// handle attributes of repeating tags
				if (is_numeric ($key) && is_array ($value)) {
					foreach ($value as $sub_key => $sub_value) {
						if (strpos ($sub_key, '@') === 0) {
							$attrs .= ' ' . substr ($sub_key, 1) . '="' . $this->_xml_entities ($sub_value) . '"';
							unset ($value[$sub_key]);
							continue;
						}
					}
				}

				if (strpos ($key, '@') === 0) {
					$attrs .= ' ' . substr ($key, 1) . '="' . $this->_xml_entities ($value) . '"';
					continue;
				}
				$res .= $this->_build_xml ($key, $value);
				$keys = array_keys ($v);
				if (is_numeric ($key) && $key !== array_pop ($keys)) {
					// reset attributes on repeating tags
					if (is_array ($value)) {
						$res = str_replace ('<' . $k . '{{attributes}}>', '<' . $k . $attrs . '>', $res);
						$attrs = '';
					}
					$res .= '</' . $k . ">\n<" . $k . '{{attributes}}>';
				}
			}
		} else {
			$res .= $this->_xml_entities ($v);
		}
		if (! is_numeric ($k)) {
			$res .= '</' . $k . ">\n";
		}
		$res = str_replace ('<' . $k . '{{attributes}}>', '<' . $k . $attrs . '>', $res);
		return $res;
	}
1122449
def as_xml(self):
        
        # Build tree
        spacing = ("\n" if (self.pretty_xml) else "")
        root = Element('error', {'xmlns': I3F_NS})
        root.text = spacing
        e_parameter = Element('parameter', {})
        e_parameter.text = self.parameter
        e_parameter.tail = spacing
        root.append(e_parameter)
        if (self.text):
            e_text = Element('text', {})
            e_text.text = self.text
            e_text.tail = spacing
            root.append(e_text)
        # Write out as XML document to return
        tree = ElementTree(root)
        xml_buf = io.BytesIO()
        if (sys.version_info < (2, 7)):
            tree.write(xml_buf, encoding='UTF-8')
        else:
            tree.write(xml_buf, encoding='UTF-8',
                       xml_declaration=True, method='xml')
        return(xml_buf.getvalue().decode('utf-8'))
105636
static function simple()
    {
        $xml = self::maker(false, false, false, false, false);
        \Moxl\API::request($xml);
    }
911200
def XML(content, source=None):
    
    try:
        tree = ET.XML(content)
    except ET.ParseError as err:
        x_parse_error(err, content, source)
    return tree
278234
def sublistReader(xmlelement):
    
    #Note: actually I'm not 100% sure how this function behaves
    elements = list()
    params, children = extractParams(xmlelement)
    for child in children:
        currElement = dict()
        currElement.update(child.attrib)
        childparams, subchildren = extractParams(child)
        if childparams:
            currElement['params'] = childparams
        for subchild in subchildren:
            subchildTag = clearTag(subchild.tag)
            if 'List' in subchildTag:
                listelements, listparams = sublistReader(subchild)
                simplelist = [listelement['params'] for listelement in listelements]
                currElement[subchildTag] = simplelist
            else:
                subchildparams, _ = extractParams(subchild)
                currElement[subchildTag] = subchildparams
                if subchildTag == 'binary' and subchild.text:
                    currElement[subchildTag] = subchild.text.strip()
        elements.append(currElement)
    return elements, params
871393
def from_xml_node(cls, node):
        """"""
        return cls(name=node.find("Name").text,
                bit_position=int(node.find("Bitposition").text),
                bit_size=int(node.find("Bitsize").text),
                factor=float(node.find("Factor").text),
                offset=float(node.find("Offset").text),
                min_value=float(node.find("Minimum").text),
                max_value=float(node.find("Maximum").text))
105777
def render_as_xml(func):
    
    if inspect.isclass(func):
        setattr(func, "_renderer", xml_renderer)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, dicttoxml)
        return decorated_view
928167
def parse_xml(data, handle_units):
    """"""
    root = ET.fromstring(data)
    return squish(parse_xml_dataset(root, handle_units))
588040
function parseMwsResponse(method, headers, response, callback) {
  // if it's XML, then we an parse correctly
  if (headers && headers['content-type'] == 'text/xml') {
    xml2js.parseString(response, {explicitArray: false}, function(err, result) {
      if (err) {
        return callback(err);
      }

      if (result.ErrorResponse) {
        err = {
          Code: 'Unknown',
          Message: 'Unknown MWS error'
        };

        if (result.ErrorResponse.Error) {
          err = result.ErrorResponse.Error;
        }

        return callback(error.apiError(err.Code, err.Message, result));
      } else {
        callback(null, new Response(method, result));
      }
    });
  } else {
    callback(null, new Response(method, { "Response": response }));
  }
}
447846
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        assert node.tag.lower() == 'action'

        kwargs = {}
        args = []
        if 'id' in node.attrib:
            kwargs['id'] = node.attrib['id']
        elif 'name' in node.attrib:
            kwargs['name'] = node.attrib['name']
        elif 'description' in node.attrib:
            kwargs['description'] = node.attrib['description']
        elif 'method' in node.attrib:
            kwargs['method'] = node.attrib['method']
        elif 'mimetype' in node.attrib:
            kwargs['mimetype'] = node.attrib['mimetype']
        elif 'allowanonymous' in node.attrib:
            if node.attrib['allowanonymous'] == "yes":
                kwargs['allowanonymous'] = True

        found = False
        for subnode in node:
            if subnode.tag.lower() == 'parametercondition':
                kwargs[node.tag] = ParameterCondition.fromxml(subnode)
            elif subnode.tag in vars(clam.common.parameters):
                args.append(vars(clam.common.parameters)[subnode.tag].fromxml(subnode))
        if not found:
            raise Exception("No condition found in ParameterCondition!")
        return Action(*args, **kwargs)
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
770514
def object2xml(self, data):
        
        """
        if not self.__options['encoding']:
            self.set_options(encoding=self.__encoding)

        if self.__options['header_declare']:
            self.__tree.append(self.build_xml_header())

        root = self.__options['root']
        if not root:
            assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
                'if root not specified, the data that dict object and length must be one required.'
            root, data = data.items()[0]

        self.build_tree(data, root)
        xml = unicode(''.join(self.__tree).strip())

        if self.__options['encoding'] != self.__encoding:
            xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
        return xml
1070119
def _extract_response_xml(self, domain, response):
        
        attributes = {}
        alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
        try:
            xml_root = ET.fromstring(response._content)
            for xml_child in xml_root.findall('SD//'):
                if xml_child.tag in alexa_keys and \
                        alexa_keys[xml_child.tag] in xml_child.attrib:
                    attributes[xml_child.tag.lower(
                    )] = xml_child.attrib[alexa_keys[xml_child.tag]]
        except ParseError:
            # Skip ill-formatted XML and return no Alexa attributes
            pass
        attributes['domain'] = domain
        return {'attributes': attributes}
86645
def xml(self, indent = ""):
        """"""
        xml = "\n" + indent + "<profile>\n"
        xml += indent + " <input>\n"
        for inputtemplate in self.input:
            xml += inputtemplate.xml(indent +"    ") + "\n"
        xml += indent + " </input>\n"
        xml += indent + " <output>\n"
        for outputtemplate in self.output:
            xml += outputtemplate.xml(indent +"    ") + "\n" #works for ParameterCondition as well!
        xml += indent + " </output>\n"
        xml += indent + "</profile>\n"
        return xml
715012
function(xml) {
    var contexp, fn, formatted, indent, l, lastType, len, lines, ln, pad, reg, transitions, wsexp;
    reg = /(>)(<)(\/*)/g;
    wsexp = /[ ]*(.*)[ ]+\n/g;
    contexp = /(<.+>)(.+\n)/g;
    xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
    pad = 0;
    formatted = '';
    lines = xml.split('\n');
    indent = 0;
    lastType = 'other';
    transitions = {
      'single->single': 0,
      'single->closing': -1,
      'single->opening': 0,
      'single->other': 0,
      'closing->single': 0,
      'closing->closing': -1,
      'closing->opening': 0,
      'closing->other': 0,
      'opening->single': 1,
      'opening->closing': 0,
      'opening->opening': 1,
      'opening->other': 1,
      'other->single': 0,
      'other->closing': -1,
      'other->opening': 0,
      'other->other': 0
    };
    fn = function(ln) {
      var fromTo, j, key, padding, type, types, value;
      types = {
        single: Boolean(ln.match(/<.+\/>/)),
        closing: Boolean(ln.match(/<\/.+>/)),
        opening: Boolean(ln.match(/<[^!?].*>/))
      };
      type = ((function() {
        var results;
        results = [];
        for (key in types) {
          value = types[key];
          if (value) {
            results.push(key);
          }
        }
        return results;
      })())[0];
      type = type === void 0 ? 'other' : type;
      fromTo = lastType + '->' + type;
      lastType = type;
      padding = '';
      indent += transitions[fromTo];
      padding = ((function() {
        var m, ref1, results;
        results = [];
        for (j = m = 0, ref1 = indent; 0 <= ref1 ? m < ref1 : m > ref1; j = 0 <= ref1 ? ++m : --m) {
          results.push('  ');
        }
        return results;
      })()).join('');
      if (fromTo === 'opening->closing') {
        formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
      } else {
        formatted += padding + ln + '\n';
      }
    };
    for (l = 0, len = lines.length; l < len; l++) {
      ln = lines[l];
      fn(ln);
    }
    return formatted;
  }
1100566
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        assert node.tag.lower() == 'parametercondition'

        kwargs = {}

        found = False
        for node in node:
            if node.tag == 'if':
                #interpret conditions:
                for subnode in node:
                    operator = subnode.tag
                    parameter = subnode.attrib['parameter']
                    value = subnode.text
                    kwargs[parameter + '_' + operator] = value
                    found = True
            elif node.tag == 'then' or node.tag == 'else' or node.tag == 'otherwise':
                #interpret statements:
                for subnode in node: #MAYBE TODO LATER: Support for multiple statement in then=, else= ?
                    if subnode.tag.lower() == 'parametercondition':
                        kwargs[node.tag] = ParameterCondition.fromxml(subnode)
                    elif subnode.tag == 'meta':
                        #assume metafield?
                        kwargs[node.tag] = AbstractMetaField.fromxml(subnode)
                    elif subnode.tag.lower() == 'outputtemplate':
                        kwargs[node.tag] = OutputTemplate.fromxml(subnode)
        if not found:
            raise Exception("No condition found in ParameterCondition!")
        return ParameterCondition(**kwargs)
192940
static function simpleXmlToArray(SimpleXMLElement &$source)
  {
    $res = array();
    $children = false;
    foreach ($source as $key => $value) {
        CPS_Response::simpleXmlToArrayHelper($res, $key, $value, $children);
    }
    if ($source) {
      foreach ($source->children('www.clusterpoint.com') as $key => $value) {
        $newkey = 'cps:' . $key;
        CPS_Response::simpleXmlToArrayHelper($res, $newkey, $value, $children);
      }
    }
    if (!$children)
      return (string)$source;
    return $res;
  }