Leonidas-from-XIV / node-xml2js

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

fixes #541, add namespace to root item in builder #559

Open Omega-Ariston opened 4 years ago

Omega-Ariston commented 4 years ago

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 commented 4 years ago

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>
coveralls commented 4 years ago

Coverage Status

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