首页 > 解决方案 > 如何动态修改 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>

有没有简单的解决方案来做到这一点?

标签: node.jsxml

解决方案


最近不得不做类似的事情并最终使用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>

推荐阅读