npm中xml-writer文档的链接地址:https://www.npmjs.com/package/xml-writer
npm中的文档比较简单,而且生成本地xml文件的demo并不正确。本篇是对以上文档的更正和补充。
1 var XMLWriter = require('./node-modules/xml-writer'); // 导入xml-writer模块 2 var fs = require('fs'); // 导入文件系统模块 3 var appPath = process.execPath; // nw.exe进程所在目录 4 console.log("appPath = " + appPath); 5 var resourcePath = appPath.replace("nw.exe", "xml\\netdisk-user-cfg.xml"); // 将nw.exe进程所在目录改成生成xml文件的目录 6 console.log("resourcePath = " + resourcePath); 7 // 创建写入流 8 var ws = fs.createWriteStream(resourcePath); 9 10 // 同步读取文件内容,本段代码可不写,只是方便在console中查看 11 ws.on('close', function() { 12 console.log(fs.readFileSync(resourcePath,'UTF-8')); 13 }); 14 15 xw = new XMLWriter(true, function(string, encoding) { // 第一个参数选择true会自动排版;false不会自动排版 16 ws.write(string, encoding); 17 }); 18 19 xw.startDocument('1.0', 'UTF-8').startElement(function() { 20 return 'USER_INFOS'; 21 }).writeElement('INUSE_USERID', '1001') 22 .writeElement('INUSE_TOKENID', 'asdfasdf123123asdfasdf') 23 .writeElement('INUSE_IP', '172.16.100.7') 24 .writeElement('INUSE_PORT', '443') 25 .startElement('USER_INFO') 26 .writeElement('USERID', '1001') 27 .startElement('DISK_CFG_INFOS') 28 .startElement('DISK_CFG_INFO') 29 .writeElement('DISK_CFG_NET_ROOT_ID', '1') 30 .writeElement('DISK_CFG_NET_ROOT_NAME','NAS存储') 31 .startElement('DISK_CFG_INFOS_UP') 32 .startElement('DISK_CFG_INFO_UP') 33 .writeElement('UP_DIR_FROM','D:\\up1') 34 .writeElement('UP_DIR_TO_NAME','NAS存储\\up1') 35 .writeElement('UP_DIR_TO_ID','1\\101') 36 .writeElement('STATUS','0') 37 .endElement() 38 .endElement() 39 .startElement('DISK_CFG_INFOS_DOWN') 40 .startElement('DISK_CFG_INFO_DOWN') 41 .writeElement('DOWN_DIR_FROM_NAME','NAS存储\\down1') 42 .writeElement('DOWN_DIR_FROM_ID','1\\201') 43 .writeElement('DOWN_DIR_TO','D:\\down1') 44 .writeElement('STATUS','0') 45 .endElement() 46 .endElement() 47 .endElement() 48 .endElement() 49 .endElement() 50 .endElement(); 51 ws.end();
生成的xml文件:
<?xml version="1.0" encoding="UTF-8"?> <USER_INFOS> <INUSE_USERID>1001</INUSE_USERID> <INUSE_TOKENID>asdfasdf123123asdfasdf</INUSE_TOKENID> <INUSE_IP>172.16.100.7</INUSE_IP> <INUSE_PORT>443</INUSE_PORT> <USER_INFO> <USERID>1001</USERID> <DISK_CFG_INFOS> <DISK_CFG_INFO> <DISK_CFG_NET_ROOT_ID>1</DISK_CFG_NET_ROOT_ID> <DISK_CFG_NET_ROOT_NAME>NAS存储</DISK_CFG_NET_ROOT_NAME> <DISK_CFG_INFOS_UP> <DISK_CFG_INFO_UP> <UP_DIR_FROM>D:\up1</UP_DIR_FROM> <UP_DIR_TO_NAME>NAS存储\up1</UP_DIR_TO_NAME> <UP_DIR_TO_ID>1\101</UP_DIR_TO_ID> <STATUS>0</STATUS> </DISK_CFG_INFO_UP> </DISK_CFG_INFOS_UP> <DISK_CFG_INFOS_DOWN> <DISK_CFG_INFO_DOWN> <DOWN_DIR_FROM_NAME>NAS存储\down1</DOWN_DIR_FROM_NAME> <DOWN_DIR_FROM_ID>1\201</DOWN_DIR_FROM_ID> <DOWN_DIR_TO>D:\down1</DOWN_DIR_TO> <STATUS>0</STATUS> </DISK_CFG_INFO_DOWN> </DISK_CFG_INFOS_DOWN> </DISK_CFG_INFO> </DISK_CFG_INFOS> </USER_INFO> </USER_INFOS>