michaelkourlas / node-js2xmlparser

Popular Node.js module for parsing JavaScript objects into XML
https://www.npmjs.org/package/js2xmlparser
Apache License 2.0
222 stars 52 forks source link

Self-closing tag #54

Closed ybrodsky closed 6 years ago

ybrodsky commented 7 years ago

I don't seem to find anywhere how to create a self closing tag.

Desire:

  <One />
  <Two/>
  <Three>Some data</Three>

Json:

  {
    ???
    Three: 'Some Data'
  }
jeremija commented 7 years ago

You can use parse('test', { one: {}, two: {}, three: 'Some data}). Unfortunately this doesn't work with empty arrays:

$ node

> xml = require('js2xmlparser')
{ parse: [Function: parse] }

> xml.parse('test', {one: {}, two: {}, three: 'Some data' })
'<?xml version=\'1.0\'?>\n<test>\n    <one/>\n    <two/>\n    <three>Some data</three>\n</test>'

> xml.parse('test', {one: [], two: [], three: 'Some data' })
'<?xml version=\'1.0\'?>\n<test>\n    <three>Some data</three>\n</test>'

edit Here's a hack that works with the arrays too:

> xml.parse('test', {one: [], two: [], three: 'Some data'}, { typeHandlers: { '[object Array]': array => array.length ? array : [{}] } })
'<?xml version=\'1.0\'?>\n<test>\n    <one/>\n    <two/>\n    <three>Some data</three>\n</test>'
michaelkourlas commented 7 years ago

Per the XML spec, empty-element tags should be preferred to standard tags that are simply empty.

Accordingly, I'll change the behaviour in a future (major) version and add an option to restore the old behaviour.

michaelkourlas commented 6 years ago

This will be configurable in the next release, which should be out shortly.