Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

add `attributes` and `textNodeName` options to xml parser #15

Closed
wants to merge 2 commits into from

1 participant

Huned Botee
Huned Botee

I added a couple options (and tests) for xml2json.js that I needed and that others may find useful:

  • a textNodeKey option to override the default $t -- because I need to generate JSON that I can feed into mongodb. mongodb does not like '$' in JSON key names. When not specified, the textNodeKey option defaults to '$t'

  • an attributes option to specify whether or not the xml's nodes' attributes are converted to the JSON. The default is attributes: true which preserves the usual behavior of allowing attributes into the generated JSON.

added some commits January 31, 2012
Huned Botee options.textNodeKey specifies the json key for a node's text data. if…
… unspecified, defaults to usual $t.
1d0aff2
Huned Botee options.attributes specifies whether or not xml nodes' attributes are…
… generated in the json. if unspecified, defaults to , preserving the usual behavior of generating json that includes the node's attributes
07944ad
Huned Botee
huned commented March 06, 2014

2 years old -- surely stale by now.

Huned Botee huned closed this March 06, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Showing 2 unique commits by 1 author.

Jan 31, 2012
Huned Botee options.textNodeKey specifies the json key for a node's text data. if…
… unspecified, defaults to usual $t.
1d0aff2
Huned Botee options.attributes specifies whether or not xml nodes' attributes are…
… generated in the json. if unspecified, defaults to , preserving the usual behavior of generating json that includes the node's attributes
07944ad
This page is out of date. Refresh to see the latest.
3  README.md
Source Rendered
@@ -21,7 +21,8 @@ console.log(json);
21 21
 ```
22 22
 * if you want to get the Javascript object then you might want to invoke parser.toJson(xml, {object: true});
23 23
 * if you want a reversible json to xml then you should use parser.toJson(xml, {reversible: true});
24  
-
  24
+* if you want to override the default "$t" key name for a node's text value, specify the textNodeKey option. e.g., `parser.toJson(xml, {textNodeKey: "text"})`
  25
+* if you want to prevent xml node attributes from appearing in the json, specify attributes: false. e.g., `parser.toJson(xml, {attributes: false})`. The default behavior is attributes: true.
25 26
 
26 27
 ## License
27 28
 Copyright 2011 BugLabs Inc. All rights reserved.
15  lib/xml2json.js
@@ -7,6 +7,9 @@ var ancestors = [];
7 7
 
8 8
 var options = {}; //configuration options
9 9
 function startElement(name, attrs) {
  10
+    // if options.attributes is false, throw away attributes
  11
+    if (!options.attributes) attrs = {};
  12
+
10 13
     if (! (name in currentObject)) {
11 14
         currentObject[name] = attrs;
12 15
     } else if (! (currentObject[name] instanceof Array)) {
@@ -39,7 +42,7 @@ function text(data) {
39 42
     if (!data.length) {
40 43
         return;
41 44
     }
42  
-    currentObject['$t'] = (currentObject['$t'] || "") + data;
  45
+    currentObject[options.textNodeKey] = (currentObject[options.textNodeKey] || "") + data;
43 46
 }
44 47
 
45 48
 function endElement(name) {
@@ -47,11 +50,11 @@ function endElement(name) {
47 50
     // matches the name we started on.
48 51
     var ancestor = ancestors.pop();
49 52
     if (!options.reversible) {
50  
-        if ((Object.keys(currentObject).length == 1) && ('$t' in currentObject)) {
  53
+        if ((Object.keys(currentObject).length == 1) && (options.textNodeKey in currentObject)) {
51 54
             if (ancestor[name] instanceof Array) {
52  
-                ancestor[name].push(ancestor[name].pop()['$t']);
  55
+                ancestor[name].push(ancestor[name].pop()[options.textNodeKey]);
53 56
             } else {
54  
-                ancestor[name] = currentObject['$t'];
  57
+                ancestor[name] = currentObject[options.textNodeKey];
55 58
             }
56 59
         }
57 60
     }
@@ -71,7 +74,9 @@ module.exports = function(xml, _options) {
71 74
 
72 75
     options = {
73 76
         object: false,
74  
-        reversible: false
  77
+        reversible: false,
  78
+        textNodeKey: '$t',
  79
+        attributes: true
75 80
     };
76 81
 
77 82
     for (var opt in _options) {
18  test/test.js
@@ -47,3 +47,21 @@ fs.readdir(fixturesPath, function(err, files) {
47 47
     }
48 48
 });
49 49
 
  50
+// test options.textNodeKey custom value
  51
+var xml = '<a href="http://example.com">Example Site</a>';
  52
+var actual = parser.toJson(xml, {object: true, textNodeKey: 'hi'});
  53
+var json = '{"a":{"href":"http://example.com","hi":"Example Site"}}';
  54
+assert.deepEqual(actual, JSON.parse(json));
  55
+
  56
+// test options.textNodeKey default value
  57
+var actual = parser.toJson(xml, {object: true});
  58
+var json = json.replace('"hi":', '"$t":');
  59
+assert.deepEqual(actual, JSON.parse(json));
  60
+
  61
+console.log('[xml2json options.textNodeKey] passed');
  62
+
  63
+// test options.attributes = false
  64
+var actual = parser.toJson(xml, {object: true, attributes: false});
  65
+var json = '{"a": "Example Site"}'
  66
+assert.deepEqual(actual, JSON.parse(json));
  67
+console.log('[xml2json options.attributes] passed');
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.