@@ -2,10 +2,31 @@ var Xml = require('xmlbuilder')
22
33module . exports = h
44
5- var proto = { }
5+ var proto = {
6+ constructor : h
7+ }
8+
69Object . defineProperty ( proto , 'toXml' , {
710 value : function ( options ) {
8- return Xml . create ( this ) . end ( options )
11+
12+ var root = Xml . create ( this . name , this . attributes )
13+ addChildren . call ( root , this . childNodes )
14+
15+ function addChildren ( child ) {
16+ var parent = this
17+ if ( Array . isArray ( child ) ) {
18+ child . forEach ( addChildren , parent )
19+ } else if ( typeof child === 'string' ) {
20+ parent . text ( child )
21+ } else if ( child instanceof Object ) {
22+ if ( child . name ) {
23+ var node = parent . element ( child . name , child . attributes )
24+ addChildren . call ( node , child . childNodes )
25+ }
26+ }
27+ }
28+
29+ return root . toString ( options )
930 } ,
1031 writable : true ,
1132 configurable : true ,
@@ -15,25 +36,13 @@ Object.defineProperty(proto, 'toXml', {
1536function h ( name , attr , children ) {
1637 var obj = Object . create ( proto )
1738
18- obj [ name ] = [ ]
19-
20- if ( Array . isArray ( attr ) ) {
39+ if ( Array . isArray ( attr ) && ! children ) {
2140 children = attr
22- attr = null
23- }
24-
25- if ( attr && Object . keys ( attr ) . length ) {
26- var mappedAttributes = { }
27- for ( var k in attr ) {
28- mappedAttributes [ '@' + k ] = attr [ k ]
29- }
30- obj [ name ] . push ( mappedAttributes )
31- }
32-
33-
34- if ( children ) {
35- obj [ name ] . push ( children )
41+ attr = { }
3642 }
3743
44+ obj . name = name
45+ obj . attributes = attr
46+ obj . childNodes = children
3847 return obj
3948}
0 commit comments