You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fast-xml-parser为XML根数组标签添加属性的问题

使用fast-xml-parser生成带属性的sitemap.xml问题解决

我用fast-xml-parser写脚本自动生成网站的sitemap.xml,其他功能都正常,唯独没法给根标签<urlset>加上xmlns和xmlns:xhtml两个属性。

期望生成的XML如下:

<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>

我当前的Node.js代码是这样的:

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

// 这是用同一库解析上面XML得到的结构,但我没法给根标签加属性
const test = { 
    "urlset": [ // 这里没法定义属性
        { url: [ { loc: "https://example.com/README.txt", lastmod: "12-27-2024" } ] },
        { url: [ { loc: "https://example.com/robots.txt", lastmod: "12-27-2024" } ] },
    ],
    ":@": { // 这个对生成的XML没有作用
        "@_xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9",
        "@_xmlns:xhtml": "http://www.w3.org/1999/xhtml",
    }
};

builder.build(test);

我试了各种builder配置都没解决,想问下这个需求能实现吗?


可以实现,问题出在你对根节点结构的定义上。fast-xml-parser要求根节点的属性要和节点内容放在同一个对象里,而不是单独的:@字段,同时urlset不应该是数组(因为它是唯一的根节点),里面的url才是数组。

修正后的代码如下:

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

const test = { 
    "urlset": {
        // 根节点的属性直接定义在这里
        "@_xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9",
        "@_xmlns:xhtml": "http://www.w3.org/1999/xhtml",
        // url是数组,包含所有url条目
        "url": [
            { loc: "https://example.com/README.txt", lastmod: "12-27-2024" },
            { loc: "https://example.com/robots.txt", lastmod: "12-27-2024" }
        ]
    }
};

console.log(builder.build(test));

关键说明:

  • 根节点urlset是一个对象而非数组,符合XML单根节点的规则
  • 属性@_xmlns和@_xmlns:xhtml直接作为urlset对象的属性,匹配fast-xml-parser的属性定义逻辑
  • url字段设为数组,包含所有<url>节点数据,这样就能生成你期望的XML结构

内容的提问来源于stack exchange,提问作者user19804467

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 09:07:28