node-xml2js
node-xml2js copied to clipboard
Builder: for each item in children array, I get "[object Object]"
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]?
-
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>
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 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>
Perfect, thanks. I wish this would have been documented with the $ and _ usage.
@hadesflames - close issue?
Just ran into this, I also think this should be added to the documentation before closing.
@hadesflames - close issue?
Sorry never saw this, I'm not the one that opened the issue though.