Skip to content

Instantly share code, notes, and snippets.

@bluepapa32
Created March 23, 2011 03:39
Show Gist options
  • Select an option

  • Save bluepapa32/882574 to your computer and use it in GitHub Desktop.

Select an option

Save bluepapa32/882574 to your computer and use it in GitHub Desktop.
JavaScript DOM 版 KeyValue -> XML (Only Firefox)
<html>
<head>
<title>KeyValue to XML with JavaScript DOM</title>
<script type="text/javascript" src="https://gist.github.com/raw/882574/71850ee58b0e489814ddd03fa2f627b41e0c264c/KeyValueXML.js"></script>
</head>
</html>
var kvmap = {
key1: "value1",
key2: "value2",
key3: {
"key3-1" : "value3-1",
"key3-2" : "value3-2",
}
}
var xml = document.implementation.createDocument("", "", null);
function $E(name, attrs, v) {
var e = xml.createElement(name);
for (attr in attrs) { e.setAttribute(attr, attrs[attr]) }
if (typeof v == 'string') {
e.appendChild(xml.createTextNode(v));
} else {
for (k in v) { e.appendChild($E(k, null, v[k])); }
}
e.toString = function() { return new XMLSerializer().serializeToString(e) }
return e;
}
var expect = '<langs type="current"><key1>value1</key1><key2>value2</key2><key3><key3-1>value3-1</key3-1><key3-2>value3-2</key3-2></key3></langs>';
alert($E('langs', { 'type': 'current' }, kvmap).toString() == expect);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment