serialize CFPropertyList object to XML
 opts = {}:: Specify options: :formatted - Use indention and line breaks
428641
def to_str(opts={})
      doc = REXML::Document.new
      @doc = doc

      doc.context[:attribute_quote] = :quote

      doc.add_element 'plist', {'version' => '1.0'}
      doc.root << opts[:root].to_xml(self)

      formatter = if opts[:formatted] then
        f = REXML::Formatters::Pretty.new(2)
        f.compact = true
        f.width = Float::INFINITY
        f
      else
        REXML::Formatters::Default.new
      end

      str = formatter.write(doc.root, "")
      str1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" + str + "\n"
      str1.force_encoding('UTF-8') if str1.respond_to?(:force_encoding)

      return str1
    end
562224
def write_xml(self):
        '''
            
        '''
        order_by_specs = etree.Element('order-by-property')

        order_by_specs.attrib['type-id'] = self.typeid
        order_by_specs.attrib['property-name'] = self.property_name
        order_by_specs.attrib['direction'] = self.direction
        return order_by_specs
1017946
def to_properties(cls, config, compact=False, indent=2, key_stack=[]):
        

        def escape_value(value):
            return value.replace('=', '\\=').replace('!', '\\!').replace('#', '\\#').replace('\n', '\\\n')

        stripped_key_stack = [key.strip('"') for key in key_stack]
        lines = []
        if isinstance(config, ConfigTree):
            for key, item in config.items():
                if item is not None:
                    lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [key]))
        elif isinstance(config, list):
            for index, item in enumerate(config):
                if item is not None:
                    lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [str(index)]))
        elif isinstance(config, basestring):
            lines.append('.'.join(stripped_key_stack) + ' = ' + escape_value(config))
        elif config is True:
            lines.append('.'.join(stripped_key_stack) + ' = true')
        elif config is False:
            lines.append('.'.join(stripped_key_stack) + ' = false')
        elif config is None or isinstance(config, NoneValue):
            pass
        else:
            lines.append('.'.join(stripped_key_stack) + ' = ' + str(config))
        return '\n'.join([line for line in lines if len(line) > 0])
1331119
def toxml(self):
        

        return '<With ' + \
          (' instance="{0}"'.format(self.instance) if self.instance else '') +\
          (' list="{0}"'.format(self.list) if self.list else '') + \
          (' index="{0}"'.format(self.index) if self.index else '') + \
          ' as="{1}"/>'.format(self.instance, self.as_)
1064709
def _serialize(self, value, key, obj):
        
        param_values = {}
        for name, attr_tpl in iteritems(self.params):
            attr_name = _tpl(str(attr_tpl))
            if attr_name:
                attribute_value = _get_value(obj, attr_name, default=missing)
                if attribute_value is None:
                    return None
                if attribute_value is not missing:
                    param_values[name] = attribute_value
                else:
                    raise AttributeError(
                        "{attr_name!r} is not a valid "
                        "attribute of {obj!r}".format(attr_name=attr_name, obj=obj)
                    )
            else:
                param_values[name] = attr_tpl
        return url_for(self.endpoint, **param_values)
205946
def xml(self, indent = ""):
        """"""
        xml = indent + "<" + self.__class__.__name__
        xml += ' id="'+self.id + '"'
        xml += ' name="'+xmlescape(self.name) + '"'
        xml += ' description="'+xmlescape(self.description) + '"'
        if self.paramflag:
            xml += ' flag="'+self.paramflag + '"'
        for key, v in self.kwargs.items():
            if key not in ('value','error','name','description','flag','paramflag', 'validator'):
                if isinstance(v, bool):
                    xml += ' ' + key + '="' + str(int(v))+ '"'
                elif isinstance(v, list):
                    xml += ' ' + key + '="'+xmlescape(",".join(v))+ '"'
                elif isinstance(v, str)  or ( sys.version < '3' and isinstance(v, unicode)): #pylint: disable=undefined-variable
                    xml += ' ' + key + '="'+xmlescape(v)+ '"'
                else:
                    xml += ' ' + key + '="'+xmlescape(str(v))+ '"'
        if self.hasvalue:
            if sys.version < '3':
                xml += ' value="'+xmlescape(unicode(self.value)) + '"' #pylint: disable=undefined-variable
            else:
                xml += ' value="'+xmlescape(str(self.value)) + '"'
        if self.error:
            xml += ' error="'+xmlescape(self.error) + '"'
        xml += " />"
        return xml
950129
function format(obj, opts, fn) {
  if (typeof opts === 'function') {
    fn = opts; opts = {};
  }

  opts = opts || {};
  if (Array.isArray(opts.filter) || typeof opts.filter === 'string') {
    obj = filter(obj, opts.filter);
  }

  var keys = Object.keys(obj);
  var len = keys.length, i = 0;
  var str = '';
  var total = len;

  while (len--) {
    var fp = keys[i++];
    var ctx = context(read(fp), fn);
    var name = basename(fp);
    str += heading(name, fp);

    var list = obj[fp];
    var methods = Object.keys(list);
    total += methods.length;

    str += listify(fp, methods, ctx);
  }

  var res = {};
  res.list = str;
  res.total = total;
  return res;
}
1146024
def _serialize(self, target_obj, data_type=None, **kwargs):
        
        key_transformer = kwargs.get("key_transformer", self.key_transformer)
        keep_readonly = kwargs.get("keep_readonly", False)
        if target_obj is None:
            return None

        attr_name = None
        class_name = target_obj.__class__.__name__

        if data_type:
            return self.serialize_data(
                target_obj, data_type, **kwargs)

        if not hasattr(target_obj, "_attribute_map"):
            data_type = type(target_obj).__name__
            if data_type in self.basic_types.values():
                return self.serialize_data(
                    target_obj, data_type, **kwargs)

        # Force "is_xml" kwargs if we detect a XML model
        try:
            is_xml_model_serialization = kwargs["is_xml"]
        except KeyError:
            is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model())

        serialized = self._create_serialized_base(target_obj)  # Could be JSON or XML
        try:
            attributes = target_obj._attribute_map
            for attr, attr_desc in attributes.items():
                attr_name = attr
                if not keep_readonly and target_obj._validation.get(attr_name, {}).get('readonly', False):
                    continue

                if attr_name == "additional_properties" and attr_desc["key"] == '':
                    if target_obj.additional_properties is not None:
                        serialized.update(target_obj.additional_properties)
                    continue
                try:
                    ### Extract sub-data to serialize from model ###
                    orig_attr = getattr(target_obj, attr)
                    if target_obj.is_xml_model():
                        pass # Don't provide "transformer" for XML for now. Keep "orig_attr"
                    else: # JSON
                        keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr)
                        keys = keys if isinstance(keys, list) else [keys]

                    ### Serialize this data ###
                    kwargs["serialization_ctxt"] = attr_desc
                    new_attr = self.serialize_data(orig_attr, attr_desc['type'], **kwargs)

                    ### Incorporate this data in the right place ###
                    if is_xml_model_serialization:
                        xml_desc = attr_desc['xml']
                        xml_name = xml_desc['name']
                        if "attr" in xml_desc and xml_desc["attr"]:
                            serialized.set(xml_name, new_attr)
                            continue
                        if isinstance(new_attr, list):
                            serialized.extend(new_attr)
                        elif isinstance(new_attr, ET.Element):
                            # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces.
                            if 'name' not in getattr(orig_attr, '_xml_map', {}):
                                splitted_tag = new_attr.tag.split("}")
                                if len(splitted_tag) == 2: # Namespace
                                    new_attr.tag = "}".join([splitted_tag[0], xml_name])
                                else:
                                    new_attr.tag = xml_name
                            serialized.append(new_attr)
                        else:  # That's a basic type
                            # Integrate namespace if necessary
                            local_node = _create_xml_node(
                                xml_name,
                                xml_desc.get('prefix', None),
                                xml_desc.get('ns', None)
                            )
                            local_node.text = str(new_attr)
                            serialized.append(local_node)
                    else: # JSON
                        for k in reversed(keys):
                            unflattened = {k: new_attr}
                            new_attr = unflattened

                        _new_attr = new_attr
                        _serialized = serialized
                        for k in keys:
                            if k not in _serialized:
                                _serialized.update(_new_attr)
                            _new_attr = _new_attr[k]
                            _serialized = _serialized[k]
                except ValueError:
                    continue

        except (AttributeError, KeyError, TypeError) as err:
            msg = "Attribute {} in object {} cannot be serialized.\n{}".format(
                attr_name, class_name, str(target_obj))
            raise_with_traceback(SerializationError, msg, err)
        else:
            return serialized
492910
def to_xfdf
      builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
        xml.xfdf('xmlns' => 'http://ns.adobe.com/xfdf/', 'xml:space' => 'preserve') {
          xml.f(href: options[:file]) if options[:file]
          xml.ids(original: options[:id], modified: options[:id]) if options[:id]
          xml.fields {
            @fields.each do |field, value|
              xml.field(name: field) {
                if value.is_a? Array
                  value.each { |item| xml.value(item.to_s) }
                else
                  xml.value(value.to_s)
                end
              }
            end
          }
        }
      end
      builder.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML)
    end
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)
1370401
function serialize(value, indent) {
    "use strict";
    if (isArray(value)) {
        value = value.map(function _map(prop) {
            return isFunction(prop) ? prop.toString().replace(/\s{2,}/, '') : prop;
        });
    }
    return JSON.stringify(value, null, indent);
}
1012022
def _serialize(self, convert_to_key_and_value, ignore_missing=False):
        

        serialized = {}
        properties = self._get_property_names(self)

        def get_property_detail(name):
            p = [p for p in self._property_details if p.name == name]
            return None if len(p) == 0 else p[0]

        for p in properties:
            pd = get_property_detail(p)
            value = self._property_to_field(p, pd)
            field_name = p if not pd else pd.to_field_name()

            if value is None or (ignore_missing and not value) or (pd and pd.unsent):
                continue
            else:
                key, value = convert_to_key_and_value(field_name, value, pd)
                if key:
                    serialized[key] = value

        return serialized
1002365
function formatProperties (properties) {
    const result = {}
    Object.keys(properties).forEach(key => {
      debug('formatProperties: key: ' + key)
      if (properties.hasOwnProperty(key)) {
        result[ key ] = _.clone(properties[ key ])
        result[ key ].type = properties[ key ].type.name
      }
    })
    return result
  }
843925
def serialize
      format = self.class.default_options[:format]
      if format.nil?
        to_serializable
      elsif format == :json
        to_serializable.to_json
      else
        fail FormatNotSupportedError
      end
    end
1212857
def serializeFields(obj, order=None):
    
    fields = []
    if order is None:
        fields = [backslashEscape(val) for val in obj]
    else:
        for field in order:
            escapedValueList = [backslashEscape(val) for val in
                                toList(getattr(obj, field))]
            fields.append(','.join(escapedValueList))
    return ';'.join(fields)
269836
def to_json(cls, config, compact=False, indent=2, level=0):
        
        lines = ""
        if isinstance(config, ConfigTree):
            if len(config) == 0:
                lines += '{}'
            else:
                lines += '{\n'
                bet_lines = []
                for key, item in config.items():
                    bet_lines.append('{indent}"{key}": {value}'.format(
                        indent=''.rjust((level + 1) * indent, ' '),
                        key=key.strip('"'),  # for dotted keys enclosed with "" to not be interpreted as nested key
                        value=cls.to_json(item, compact, indent, level + 1))
                    )
                lines += ',\n'.join(bet_lines)
                lines += '\n{indent}}}'.format(indent=''.rjust(level * indent, ' '))
        elif isinstance(config, list):
            if len(config) == 0:
                lines += '[]'
            else:
                lines += '[\n'
                bet_lines = []
                for item in config:
                    bet_lines.append('{indent}{value}'.format(
                        indent=''.rjust((level + 1) * indent, ' '),
                        value=cls.to_json(item, compact, indent, level + 1))
                    )
                lines += ',\n'.join(bet_lines)
                lines += '\n{indent}]'.format(indent=''.rjust(level * indent, ' '))
        elif isinstance(config, basestring):
            lines = json.dumps(config)
        elif config is None or isinstance(config, NoneValue):
            lines = 'null'
        elif config is True:
            lines = 'true'
        elif config is False:
            lines = 'false'
        else:
            lines = str(config)
        return lines
133774
private void toXml(final String indent, final StringBuffer xml) {
		String primitiveString = formatSimpleValue();

		xml.append(indent);
		xml.append(isPrimitive() ? "<primitive" : "<object");

		if (refNode == null) {
			xml.append(" id=\"").append(id).append('"');

			if (fieldName != null) {
				xml.append(" field=\"").append(fieldName).append('"');
			}

			if (primitiveString != null) {
				primitiveString = WebUtilities.encode(primitiveString);
				xml.append(" value=\"").append(primitiveString).append('"');
			}

			if (type != null) {
				xml.append(" type=\"").append(type).append('"');
			}

			xml.append(" size=\"").append(getSize()).append('"');

			if (getChildCount() == 0) {
				xml.append("/>\n");
			} else {
				xml.append(">\n");

				String newIndent = indent + "  ";

				for (int i = 0; i < getChildCount(); i++) {
					((ObjectGraphNode) getChildAt(i)).toXml(newIndent, xml);
				}

				xml.append(indent);
				xml.append(isPrimitive() ? "</primitive>\n" : "</object>\n");
			}
		} else {
			if (fieldName != null) {
				xml.append(" field=\"").append(fieldName).append('"');
			}

			xml.append(" refId=\"").append(refNode.id).append('"');

			if (refNode.value == null) {
				xml.append(" type=\"").append(refNode.type).append('"');
			} else {
				xml.append(" type=\"").append(refNode.value.getClass().getName()).append('"');
			}

			xml.append(" size=\"").append(OBJREF_SIZE).append('"');

			xml.append("/>\n");
		}
	}