node-xml2js icon indicating copy to clipboard operation
node-xml2js copied to clipboard

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

Open amokrunner opened this issue 4 years ago • 7 comments

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]?

amokrunner avatar Mar 04 '20 14:03 amokrunner

- 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>

Omega-Ariston avatar Mar 06 '20 00:03 Omega-Ariston

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>

aldobarr avatar Mar 15 '20 20:03 aldobarr

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>

Omega-Ariston avatar Mar 18 '20 02:03 Omega-Ariston

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

aldobarr avatar Mar 18 '20 16:03 aldobarr

@hadesflames - close issue?

knoxcard2 avatar Apr 05 '20 05:04 knoxcard2

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

basicdays avatar Aug 17 '22 21:08 basicdays

@hadesflames - close issue?

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

aldobarr avatar Aug 17 '22 22:08 aldobarr