我正在使用 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>
然后,我调用我的 updateXML 控制器向其中添加数据。
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?
}
谢谢