How do you add attribute to array element with xml2js?

1.2k Views Asked by At

I'm trying to figure out how to add attributes to an array element

I get an error Error: Invalid character in name when trying to build the following XML from an object.

<?xml version="1.0" encoding="UTF-8"?>
<Requests xmlns="http://example.com">
    <Request>
    </Request>
    <Request>
    </Request>
</Requests>

Here is my object

let myObject = {
 Requests:[
   {$:{xmlns:"http://example.com"}},
   {Request:{}},
   {Request:{}}
  ]
}
let builder = new xml2js.Builder();
let xml = builder.buildObject(myObject);
console.log(xml)

I've also tried wrapping the name in quotes

{"$":{"xmlns":"http://example.com"}},

Stripping out the attribute declaration altogether produces the desired XML but obviously leaves out the needed attribute

<?xml version="1.0" encoding="UTF-8"?>
<Requests>
    <Request>
    </Request>
    <Request>
    </Request>
</Requests>
1

There are 1 best solutions below

0
On

I suppose you should try this:

let myObject = {
 Requests:{
   $:{xmlns:"http://example.com"},
   Request:[{}, {}]
}