Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.87k stars 601 forks source link

Builder: for each item in children array, I get "[object Object]" #561

Open amokrunner opened 4 years ago

amokrunner commented 4 years ago

The following:

let a = [{bar:1},{bar:2},{bar:3}]
let o = {
  foo: {
    _: a
  }
}
var builder = new xml2js.Builder()
var xml = builder.buildObject(o)

Returns this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
  <bar>1</bar>
  <bar>2</bar>
  <bar>3</bar>
  [object Object],[object Object],[object Object]
</foo>

How do I get rid of the [object Object]?

Omega-Ariston commented 4 years ago

- attribute can only be used to generate text node. You can use the following way to generate the correct child node:

    let a = [{ bar: 1 }, { bar: 2 }, { bar: 3 }]

    var builder = new xml2js.Builder({rootName:"foo"});
    var xml = builder.buildObject(a);

    console.log(xml);

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
  <bar>1</bar>
  <bar>2</bar>
  <bar>3</bar>
</foo>
aldobarr commented 4 years ago

I have a similar issue except my output needs to be something along the lines of:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Fields>
    <Inputs>
        <Foo name="some string">
            <Bar>1</Bar>
            <Bar>2</Bar>
            <Bar>3</Bar>
            <Bar>4</Bar>
        </Foo>
    </Inputs>
</Fields>
Omega-Ariston commented 4 years ago

I have a similar issue except my output needs to be something along the lines of:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Fields>
    <Inputs>
        <Foo name="some string">
            <Bar>1</Bar>
            <Bar>2</Bar>
            <Bar>3</Bar>
            <Bar>4</Bar>
        </Foo>
    </Inputs>
</Fields>

I wrote a simple demo for this case. Is it what you need? :)

const xmlObj = {
    "Fields": {
        "Inputs": {
            "Foo": {
                "$": {
                    "name": "some string"
                },
                "Bar": [
                    "1",
                    "2",
                    "3",
                    "4"
                ]
            }
        }
    }
};

const builder = new xml2js.Builder();
const xmlstr = builder.buildObject(xmlObj);
console.log(xmlstr);

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Fields>
  <Inputs>
    <Foo name="some string">
      <Bar>1</Bar>
      <Bar>2</Bar>
      <Bar>3</Bar>
      <Bar>4</Bar>
    </Foo>
  </Inputs>
</Fields>
aldobarr commented 4 years ago

Perfect, thanks. I wish this would have been documented with the $ and _ usage.

knoxcard2 commented 4 years ago

@hadesflames - close issue?

basicdays commented 2 years ago

Just ran into this, I also think this should be added to the documentation before closing.

aldobarr commented 2 years ago

@hadesflames - close issue?

Sorry never saw this, I'm not the one that opened the issue though.