xml2js 没有按预期编写
xml2js not writing as expected
鉴于此 XML 布局:
<config>
<Nightly>
<VersionNumber>1.10.0</VersionNumber>
</Nightly>
</config>
以及此代码 (based on this article):
NewVersionNumber = '1.10.1';
fs.readFile("../config.xml", "utf-8", (err, data) => {
xml2js.parseString(data, (err, result) => {
result.config.Nightly.VersionNumber = NewVersionNumber;
const builder = new xml2js.Builder();
const xml = builder.buildObject(result);
fs.writeFile('../config.xml', xml, (err) => {
if (err) {
throw err;
}
});
});
我得到这个结果:
<config>
<Nightly>
<VersionNumber>1.10.0</VersionNumber>
</Nightly>
<Nightly>1.10.1</Nightly>
</config>
我做错了什么?它的目标是 更新 config.Nightly.VersionNumber
值。
所以我通过简单地向每个元素添加 [0]
来解决这个问题:
result.config.Nightly[0].AppName[0] = message.AppName;
result.config.Nightly[0].VersionNumber[0] = message.VersionNumber;
result.config.Nightly[0].Branch[0] = message.Branch;
我将此作为答案发布,因为它已修复,但我希望看到其他答案或解释。
尝试使用 explicitArray:false
参数:
xml2js.parseString(data, {explicitArray:false}, (err, result) => {
看这里:
explicitArray (default: true): Always put child nodes in an array if
true; otherwise an array is created only if there is more than one.
鉴于此 XML 布局:
<config>
<Nightly>
<VersionNumber>1.10.0</VersionNumber>
</Nightly>
</config>
以及此代码 (based on this article):
NewVersionNumber = '1.10.1';
fs.readFile("../config.xml", "utf-8", (err, data) => {
xml2js.parseString(data, (err, result) => {
result.config.Nightly.VersionNumber = NewVersionNumber;
const builder = new xml2js.Builder();
const xml = builder.buildObject(result);
fs.writeFile('../config.xml', xml, (err) => {
if (err) {
throw err;
}
});
});
我得到这个结果:
<config>
<Nightly>
<VersionNumber>1.10.0</VersionNumber>
</Nightly>
<Nightly>1.10.1</Nightly>
</config>
我做错了什么?它的目标是 更新 config.Nightly.VersionNumber
值。
所以我通过简单地向每个元素添加 [0]
来解决这个问题:
result.config.Nightly[0].AppName[0] = message.AppName;
result.config.Nightly[0].VersionNumber[0] = message.VersionNumber;
result.config.Nightly[0].Branch[0] = message.Branch;
我将此作为答案发布,因为它已修复,但我希望看到其他答案或解释。
尝试使用 explicitArray:false
参数:
xml2js.parseString(data, {explicitArray:false}, (err, result) => {
看这里:
explicitArray (default: true): Always put child nodes in an array if true; otherwise an array is created only if there is more than one.