Skip to content

Commit

Permalink
Get parser working with arrays (e.g. <root><items><item>1</item><item…
Browse files Browse the repository at this point in the history
…>2</item><item>3</item></items></root>)
  • Loading branch information
kyleslattery committed Jan 19, 2010
1 parent 281b5c8 commit ca8496b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 7 deletions.
29 changes: 23 additions & 6 deletions lib/xml2object.js
Expand Up @@ -12,7 +12,6 @@ var Parser = function() {

// TODO: Make this support prefixes and URIs
cb.onStartElementNS(function(elem, prefix, uri) {

// Determine current object before this element
if(current_tree.length == 0) {
var obj = return_object;
Expand All @@ -24,10 +23,28 @@ var Parser = function() {
}

// Initialize new object for this element and set as current_object
obj[elem] = {};
current_tree.push(elem);

current_object = obj[elem];
// Check if the element already exists. If it does, this should be an array.
if(typeof(obj[elem]) === "undefined") {
// Doesn't already exist, so just create a standard object.
obj[elem] = {};

current_object = obj[elem];
} else if(obj[elem].constructor == Array) {
// It does already exist, and it's already an array
current_object = {};
obj[elem].push(current_object);
} else {
// It already exists, and it's an object, so it needs to be changed to an array
var old_obj = obj[elem];

current_object = {};

obj[elem] = [];
obj[elem].push(old_obj);
obj[elem].push(current_object);
}
current_tree.push(elem);
});

cb.onCharacters(addContent);
Expand All @@ -41,6 +58,7 @@ var Parser = function() {

cb.onEndElementNS(function(elem, prefix, uri) {
current_tree.pop();

if(current_tree.length == 0) {
promise.emitSuccess(return_object);
}
Expand All @@ -57,6 +75,5 @@ var Parser = function() {

// Returns eventEmitter
exports.parseString = function(string) {
var parser = new Parser();
return parser.parseString(string);
return new Parser().parseString(string);
}
31 changes: 30 additions & 1 deletion test/xml2object_test.js
Expand Up @@ -27,4 +27,33 @@ describe("Basic XML String parse with parseString")
}
}
})
})
})

describe("XML String with array")
before(function() {
this.xml = "<root><items><item>test1</item><item>test2</item><item>test3</item></items></root>";
this.response = xml2object.parseString(this.xml);
})

it("should return object with array of items", function() {
var response = this.response.wait();

assert.deepEqual(response, {
root: {
items: {
item: [
{
content: "test1"
},
{
content: "test2"
},
{
content: "test3"
}
]
}
}
})
})

0 comments on commit ca8496b

Please sign in to comment.