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

fixes #541, add namespace to root item in builder

Open Omega-Ariston opened this issue 5 years ago • 2 comments

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>

Omega-Ariston avatar Feb 26 '20 06:02 Omega-Ariston

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>

Omega-Ariston avatar Feb 26 '20 06:02 Omega-Ariston

Coverage Status

Coverage remained the same at 97.727% when pulling 23c218a4987415aaca809a2ad28e612935491ea7 on Omega-Ariston:fix-issue541 into 8fc5b926846cd4ef9a2dbccd411705e0c110a708 on Leonidas-from-XIV:master.

coveralls avatar Feb 26 '20 06:02 coveralls