chapel1337
chapel1337

Reputation: 17

Adding attributes to an array tag when building with JS (Fast-xml-parser)

I'm writing a script to automatically generate a sitemap.xml for my website with fast-xml-parser, and have been able to get everything working besides building the root tag with two attributes.

The expected xml output is below:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <url>
    <loc>https://example.com/README.txt</loc>
    <lastmod>12-27-2024</lastmod>
  </url>
  <url>
    <loc>https://example.com/robots.txt</loc>
    <lastmod>12-27-2024</lastmod>
  </url>
</urlset>

The NodeJs code being used to build the xml:

const builder = new fastXml.XMLBuilder({ 
    format: true, 
    oneListGroup: true, 
    ignoreAttributes: false, 
    attributeNamePrefix: "@_" 
});

// below is what's given when parsing the above xml using the same library
const test = { 
    "urlset": [ // unable to define attributes here
        { url: [ { loc: "https://example.com/README.txt", lastmod: "12-27-2024" } ] },
        { url: [ { loc: "https://example.com/robots.txt", lastmod: "12-27-2024" } ] },
    ],
    ":@": { // has no effect on the built xml
        "@_xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9",
        "@_xmlns:xhtml": "http://www.w3.org/1999/xhtml",
    }
};

builder.build(test);

I have tried multiple different options with the builder and couldn't find anything answering this online. Is this possible?

Upvotes: 0

Views: 35

Answers (0)

Related Questions