NodeJS 检查 XML 元素是否存在并添加或删除

NodeJS checking if XML element exists and add or delete

我正在使用 NodeJS XML。我一直在使用 xmlbuilder 创建我的 XML。问题是现在我需要检查一个元素是否已经存在并删除或更新它。 例如,我有以下 XML

<?xml version="1.0"?>
<listings>
    <listing>
        <id>1</id>
        <name>TEST</name>
        <description>TEST</description>
    </listing>
    <listing>
        <id>2</id>
        <name>TEST</name>
        <description>TEST</description>
    </listing>
</listings>

然后,我调用更新XML 控制器向其添加数据。

const builder = require('xmlbuilder');
const fs = require('fs');
const path = require("path");

exports.updateXML = async (req, res, next) => {
    const data = req.body.data;
    /* 
        For example data is
        {
            id: 2,
            name: "Test2",
            description: "Desc2"
        }
    */

    const xmlFile = fs.readFileSync(path.resolve(__dirname, "./oodle.xml"), 'utf8');
    
    if(/*How do I check if the xmlFile has a <id> === data.id?*/) {
        // If id matches. How can I delete the whole <listing> node for that id?
    }

    const newListing = builder.create('listing');
    newListing.ele("id", data.id);
    newListing.ele("name", data.name);
    newListing.ele("description", data.description);

    // How can I add the newListing node to the xmlFile?
}

谢谢

我认为没有必要删除具有重复 <id> 的节点,创建一个新的 <listing> 节点,然后将其插入 xml。至少就你问题中的样本 xml 而言,你可以只修改相关 <listing> 节点的文本子节点。

大致如下:

const { select } = require('xpath');

let query = `//listing[./id[./text()="${data.id}"]]`;

const nodes = select(query, doc.node);
 nodes.forEach(function (node) {
    nam = select('.//name/text()',node)
    desc = select('.//description/text()',node)
    nam[0].data = data.name;
    desc[0].data = data.description;
  });
 const serializedXML = doc.end({ format: 'xml', prettyPrint: true });

 console.log(serializedXML)

输出:

<?xml version="1.0"?>
<listings>
  <listing>
    <id>1</id>
    <name>TEST</name>
    <description>TEST</description>
  </listing>
  <listing>
    <id>2</id>
    <name>Test2</name>
    <description>Desc2</description>
  </listing>
</listings>