oozcitak / xmlbuilder-js

An XML builder for node.js
MIT License
921 stars 110 forks source link

Empty Array from JSON generates Element #190

Closed kaipaysen closed 5 years ago

kaipaysen commented 5 years ago

Whats wrong?

Building a xml from a json object with an empty array creates an unexpected element in the xml. (Version 10.1.1)

Code

        let jsonData = { 
            root: {
                item: []
            } 
        };
        console.log(xmlbuilder
            .create(jsonData, { encoding: 'utf-8' })
            .end({ pretty: true })
        );

Output

<?xml version="1.0" encoding="utf-8"?>
<root>
  <item/>
</root>

expected Output

<?xml version="1.0" encoding="utf-8"?>
<root />
oozcitak commented 5 years ago

This is not a bug. { item: [] } is interpreted as a node (item) without any child nodes ([]). Accordingly a single node without children are created (<item/>).

kaipaysen commented 5 years ago

Ok, well, just to get it right:

item: [] equals item: {} equals item: [{}]

This does feel a bit wobbly. I'd totally agree about the 2nd and 3rd case producing one empty "item" element. An empty array producing an empty element seems to be just wrong. How can an element be created from nothing? Whats the rational behind that decision?

oozcitak commented 5 years ago

I gave this some more thought. You are right about arrays:

Simran-B commented 5 years ago

Hm, what about item: null or item: undefined (not in JSON, only JS)?

kaipaysen commented 5 years ago

Good point @Simran-B. In both cases I'd expect no element.

Case Expected Output
item: null
item: undefined
item: []
item: {} <item />
item: [{}] <item />
oozcitak commented 5 years ago

Fixed by 66f81657302e5814b698bf537043a46fc7287db2, be07739fc6a42504111c174763de806b39b3db02 and 782540c408a8fdbe1a425f16f67644fbd9b60492.