Skip to content

Instantly share code, notes, and snippets.

@lordnox
Created January 5, 2012 17:04
Show Gist options
  • Save lordnox/1566144 to your computer and use it in GitHub Desktop.
Save lordnox/1566144 to your computer and use it in GitHub Desktop.
Obj2XML Parser Coffeescript
###
Object 2 XML Parser
@author Tobias Kopelke <[email protected]>
based on jsontoxml from Ryan Day @ https://github.com/soldair/node-jsontoxml
Example of 'special' object properties
node =
name: 'node-name'
attributes: 'node-attribs'
content: 'node-content'
children: ['node', 'node']
###
parser = (options) ->
extract = [options.name, options.attributes, options.content, options.children]
# render the attributes
process_attribs = (attribs) ->
switch typeof attribs
when "undefined"
return ""
when "object"
attributes = ""
for i of attribs
attributes += " " + i + "=\"" + attribs[i] + "\""
return attributes
return " " + attribs
# just build the xml string
create_xml_string = (name, attribs, content) ->
attributes = process_attribs attribs
("<" + name + attributes) + if content.length then ">" + content + "</" + name + ">" else "/>"
# fetch all the data for create_xml_string
create_xml = (node, name, content) ->
attributes = node[options.attributes]
tag = node[options.name] || name
text = node[options.content]
create_xml_string tag, attributes, (text || content)
# run through all child-nodes and render those
process_child_nodes = (nodes) ->
content = []
for own name, node of nodes
content.push process_to_xml node, name
content.join ''
# render a node
process_to_xml = (node, name) ->
if typeof node == 'object'
if node instanceof Array
content = []
node.each (child) ->
content.push process_to_xml child, name
return content.join ''
children = {}
if options.children in node
children = node[options.children]
else
# fetch all elements from the node that have no special meaning
((Object.keys node).filter (item) -> item not in extract).each (key) ->
children[key] = node[key]
# run the children to get the inner tags
content = process_child_nodes children
else
content = node
# if we have a node-name build a tag
return create_xml node, name, content if name
content
# convert an object to a xml string, including a <parent>...</parent> tag
obj_to_xml = (obj, parent) ->
process_to_xml obj, parent
# convinience function ...
json_to_xml = (json, parent) ->
try
obj = JSON.parse(json)
catch e
return false
obj_to_xml obj, parent
# return object
json_to_xml: json_to_xml
obj_to_xml: obj_to_xml
obj2xml: obj_to_xml
js2xml: obj_to_xml
# build a standard parser
module.exports = parser
name: 'name'
attributes: '@'
content: '#'
children: 'childs'
# but export the parser-maker too
module.exports.parser = parser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment