node.js - 如何动态修改 XML?
问题描述
我正在读取一个 XML 文件并将其发送到 REST API。但是在发送之前我想修改一些值。
这就是我发送数据的方式:
data = await readFile(path.resolve(__dirname, file), 'utf8');
const config = {
headers: {
'Content-Type': 'text/plain',
'Content-Length': data.length,
},
};
result = await axios.post(
'https://someRestapi.com/',
data, config,
);
例如,我想将作者姓名中的名字 Simon 更改为 Zimon。
<?xml version="1.0" encoding="UTF-8"?>
<Document schemaVersion="12"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Author>
<Name>
<First>Simon</First>
<Second>SomeName</Second>
</Name>
</Author>
</Document>
有没有简单的解决方案来做到这一点?
解决方案
最近不得不做类似的事情并最终使用fast-xml-parser。适用于您的情况,您可以执行以下操作:
const xmlString = `<?xml version="1.0" encoding="UTF-8"?>
<Document schemaVersion="12"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Author>
<Name>
<First>Simon</First>
<Second>SomeName</Second>
</Name>
</Author>
</Document>`;
const xmlToJsonParser = require('fast-xml-parser');
const J2xParser = require("fast-xml-parser").j2xParser;
const tObj = xmlToJsonParser.getTraversalObj(xmlString,{ignoreAttributes :false});
const jsonObj = xmlToJsonParser.convertToJson(tObj,{ignoreAttributes :false});
jsonObj.Document.Author.Name.First = "Zimon";
let result = new J2xParser({format:true, ignoreAttributes :false}).parse(jsonObj);
result = `<?xml version="1.0" encoding="UTF-8"?>\n${result}`;
console.log(result);
这将打印:
<?xml version="1.0" encoding="UTF-8"?>
<Document schemaVersion="12" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Author>
<Name>
<First>Zimon</First>
<Second>SomeName</Second>
</Name>
</Author>
</Document>
推荐阅读
- arrays - 如何使用 JavaScript 将 URLENCODED POST 数据发送到 API?
- python-3.x - 无法在 yocto 3.1.10 中构建 python3-wsgiref
- python - 使用 numpy.ctypeslib.as_array 从 ctypes 指针获取数组无法获取具有正确值的数组
- apache - Apache/PHP 服务器*有时* 显示目录索引而不是 wordpress 页面;有时显示用户代理不允许
- mysql - 如何在 AWS Lambda 中获取 Amazon Athena 中的表大小?
- javascript - 当这些 id 在 JavaScript 中的另一个数组中时,如何根据它们的 id 删除对象
- powerbi - 如何通过与分析服务的实时连接将 Power BI 卡中的“空白”转换为 0?
- laravel - 从 vue-select 中检索数据以填充两个不同表中的输入字段
- c# - Azure 服务总线:我应该在应用程序关闭时关闭 QueueClient 吗?
- javascript - JS:如果只有最后一个字段可能为空,是否需要可选链接?