我想使用xmlbuilder
in制作一个 XML 文件node.js
。但它的结束标签在一种情况下丢失
var root = builder.create('ENVELOPE');
root.ele('HEADER')
.ele('TALLYREQUEST').txt('Import Data').up().up()
.ele('BODY')
.ele('IMPORTDATA')
.ele('REQUESTDESC')
.ele('REPORTNAME').txt('All Masters').up()
.ele('STATICVARIABLES')
.ele('SVCURRENTCOMPANY').txt('Private Limited').up().up().up()
.ele('REQUESTDATA')
.ele('TALLYMESSAGE').att('xmlns:UDF', 'TallyUDF')
.ele('VOUCHER').att('REMOTEID', '00002285').att('VCHKEY', '0000038')
.att('VCHTYPE', 'MTC').att('ACTION', 'Create').att('OBJVIEW', 'Accounting Voucher View')
.ele('OLDAUDITENTRYIDS.LIST').att('TYPE', "NUMBER")
.ele('OLDAUDITENTRYIDS').txt('-1').up().up()
.ele('DATE').txt('20210920').up()
var xml = root.end({ pretty: true });
console.log(xml);
上面的代码将给出如下输出,这就是我想要的
<?xml version="1.0" encoding="UTF-8"?><ENVELOPE><HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST></HEADER><BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>All Masters</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>Private Limited</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="00002285" VCHKEY="0000038" VCHTYPE="MTC" ACTION="Create" OBJVIEW="Accounting Voucher View">
<OLDAUDITENTRYIDS.LIST TYPE="NUMBER">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<DATE>20210920</DATE>
</VOUCHER>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA></BODY></ENVELOPE>
但是如果我为重复的代码设置一个循环,那么它会产生一个问题
var root = builder.create('ENVELOPE');
root.ele('HEADER')
.ele('TALLYREQUEST').txt('Import Data').up().up()
.ele('BODY')
.ele('IMPORTDATA')
.ele('REQUESTDESC')
.ele('REPORTNAME').txt('All Masters').up()
.ele('STATICVARIABLES')
.ele('SVCURRENTCOMPANY').txt('Private Limited').up().up().up()
.ele('REQUESTDATA');
for (let i = 0; i < 2; i++) {
root.ele('TALLYMESSAGE').att('xmlns:UDF', 'TallyUDF')
.ele('VOUCHER').att('REMOTEID', '00002285').att('VCHKEY', '0000038')
.att('VCHTYPE', 'MTC').att('ACTION', 'Create').att('OBJVIEW', 'Accounting Voucher View')
.ele('OLDAUDITENTRYIDS.LIST').att('TYPE', "NUMBER")
.ele('OLDAUDITENTRYIDS').txt('-1').up().up()
.ele('DATE').txt('20210920').up()
}
var xml = root.end({ pretty: true });
console.log(xml);
上述代码的输出如下。最后要关闭的标签将首先关闭
<?xml version="1.0" encoding="UTF-8"?><ENVELOPE><HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST></HEADER><BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>All Masters</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>Private Limited</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA />
</IMPORTDATA></BODY><TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="00002285" VCHKEY="0000038" VCHTYPE="MTC" ACTION="Create" OBJVIEW="Accounting Voucher View">
<OLDAUDITENTRYIDS.LIST TYPE="NUMBER">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<DATE>20210920</DATE>
</VOUCHER></TALLYMESSAGE></ENVELOPE>
请帮我解决这个问题,这将是一个很大的帮助