oozcitak / xmlbuilder-js

An XML builder for node.js
MIT License
919 stars 108 forks source link

Not possible to build a list of non-unique elements non-contiguously with JSON #239

Closed jvonachen closed 4 years ago

jvonachen commented 4 years ago

I'm trying to create SVG documents. SVGs are rendered in the order that the child elements are listed in a parent element. This means that there are many examples where non-unique elements need to be listed in a specific order which is non-contiguous. As far as I can see this isn't possible using a JSON object the current state the software is in. Only contiguous lists of non-unique elements are possible. Unless I am wrong.

oozcitak commented 4 years ago

It's actually possible:

const builder = require('xmlbuilder');

const obj = {
  root: {
    '#text': [
      { node: 'value1' },
      { node: 'value2' }
      { '#comment': 'comment node' },
      { node: 'value3' },
      { node: 'value4' }
    ]
  }
};

console.log(builder.create(obj).end({ pretty: true });
<?xml version="1.0"?>
<root>
  <node>value1</node>
  <node>value2</node>
  <!-- comment node -->
  <node>value3</node>
  <node>value4</node>
</root>

The #text decorator creates a text node from its value. However if its value is an object instead of a string, it drops the #text key and passes the object value on to the ele function of its parent node; which creates nodes under parent. Above example uses this to convert arrays of JS objects under the parent root element.

jvonachen commented 4 years ago

I might use this in the future but I have found that just building the XML string without using builder or JSON is suitable for my purpose. I hope others who need this will find this message.