2

我正在使用 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?
}

谢谢

4

1 回答 1

1

我不认为真的有必要删除带有副本的节点<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>
于 2021-01-19T01:37:06.123 回答