node-xml2js
node-xml2js copied to clipboard
fixes #541, add namespace to root item in builder
This PR Closes #541
In xml2js, you can't add attribute to a node if its child nodes form an array. In this case, you can only use "-" to add text nodes.
I reckon it would be better to open the builder
object since this can largely increase the possibilities to manipulate with xml2js for more particular cases. Also, Parser can access the Parser object through parser.saxParser
.
And the problem mentioned in #541 can be solved this way:
const urls = [{ url: "node1" }, { url: "node2" }, { url: "node3" }];
const root = {
urlset: {
$: { xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9' }
}
}
const builder = new xml2js.Builder();
const rootNode = builder.build(root);
const xmlString = rootNode.ele(urls).end(xml2js.defaults["0.2"].renderOpts);
console.log(xmlString);
output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>node1</url>
<url>node2</url>
<url>node3</url>
</urlset>
Currently, xml2js only supports adding attribute to XML in this form:
const root = {
urlset: {
$: { xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9' },
url: "node1",
url2: "node2",
url3: "node3"
}
};
const builder = new xml2js.Builder();
console.log(builder.buildObject(root));
output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>node1</url>
<url2>node2</url2>
<url3>node3</url3>
</urlset>