node.js - How to manipulate a xml file and save it to disk?
问题描述
I have two xml files with exactly same structure. The only difference is the inner text of the tags. I want to replace the value in the first file with the corresponding value in the second file.
I have tried using the xml2json but the problem is it removed all the comments which I need in the final output. So currently I am using xmldom. I am able to manipulate the text but the changes are lost when I try to save the file to the disk.
var DOMParser = require("xmldom").DOMParser;
var serializer = new (require('xmldom')).XMLSerializer;
var fs = require('fs');
let firstXML = `<root>
<!--This is just a comment-->
<string name="one">SOMETHING</string>
</root>`
let secondXML = `<root>
<string name="one">ELSE</string>
</root>`
var firstDoc = new DOMParser().parseFromString(firstXML, "text/xml");
var secondDoc = new DOMParser().parseFromString(secondXML, "text/xml");
let elementsFirst = firstDoc.getElementsByTagName("string");
let elementsSecond = secondDoc.getElementsByTagName("string");
for(let i = 0; i < elementsFirst.length; ++i) {
let el = elementsFirst[i];
let name = el.getAttribute("name");
for(let j = 0; j < elementsSecond.length; ++j) {
if(name = elementsSecond[j].getAttribute("name")) {
el.firstChild.nodeValue = elementsSecond[j].firstChild.nodeValue;
break;
}
}
}
fs.writeFileSync("output.xml", serializer.serializeToString(firstDocs));
//Required output
`<root>
<!--This is just a comment-->
<string name="one">ELSE</string>
</root>`
解决方案
请不要问我为什么,但如果你替换这一行
el.firstChild.nodeValue = elementsSecond[j].firstChild.nodeValue;
有了这个
el.firstChild.data = elementsSecond[j].firstChild.nodeValue;
它将按预期工作。
PS您的if
语句中有错字,您需要===
,单=
通常会返回true
更新:找到解决方案后 - 我发现它与这个重复
推荐阅读
- curl - 使用静态 openssl (libssl.a, libcrypto.a) 静态编译 curl lib
- php - 组内的 Laravel 组不起作用,它没有看到命名空间参数
- sharepoint - 在 yaml 管道中构建 SharePoint wsp 时缺少依赖项
- python - 当我添加类权重时,训练模型会给出 ValueError
- excel - 搜索列表中的每个项目并返回所有匹配项
- excel - 如何提取PowerPoint图表中的所有轴标签
- c# - AWS 容器中的 TCP 侦听器
- javascript - 未捕获的类型错误:无法在 JavaScript.js:2 处设置 null 的属性“onclick”
- python - 为什么 Python scipy.norm.cdf 中的矢量化正态累积函数与其标量版本不同
- rest - 使用 REST API 在 Kibana 中创建警报规则失败,出现 400“无效的操作组:默认”