nodejs
几点问题:
1、怎么直接添加子节点
2、判断目录有效性
3、parseString有没有同步接口,或者通过回调来处理数据,感觉现在异步存在时序问题
4、for循环中的continue怎么表示
<?xml version="1.0" encoding="UTF-8"?> <resources xmlns:tools="http://schemas.android.com/tools" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="app_name" priority="LT">Hello World</string> <string name="save" priority="LT">Save</string> </resources> <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:tools="http://schemas.android.com/tools" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="app_name" priority="LT">你好</string> <string name="save" priority="LT">"保存"</string> </resources>
const fs = require("fs"); const xml2js = require('xml2js'); const path = require("path") // var xmlParser = new xml2js.Parser({explicitArray:false}); const xmlParser = new xml2js.Parser(); const languageDir = 'D:\\CODE\\testnodejs\\languages'; const outDir = 'D:\\CODE\\testnodejs\\languages'; const outxmlName = 'newstring.xml'; var xmlString = '<?xml version="1.0" encoding="UTF-8"?>' +'<resources xmlns:tools="http://schemas.android.com/tools" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">' +'<string></string>' +'</resources>' xmlParser.parseString(xmlString,function(err,allResult) { var allstrings = allResult.resources.string; var files = fs.readdirSync(languageDir); files.forEach(file => { var languageFilePath = path.join(languageDir, file, "string.xml"); fs.stat(languageFilePath, (statErr, stats) => { if (statErr) { if (statErr.code == 'ENOENT') { console.log("file not exist" + languageFilePath); } return; //return跳出for循环 } var data = fs.readFileSync(languageFilePath); // var data = fs.readFileSync("./languages/values/string.xml"); xmlParser.parseString(data,(parseErr,result) => { var strings = result.resources.string; strings.forEach(string => { string.$.filename = file; allstrings.push(string); }) }); }); }); delete allstrings[0]; const builder = new xml2js.Builder(); const xml = builder.buildObject(allResult); fs.writeFile(path.join(outDir, outxmlName), xml, (error) => { if (error) { throw error; } console.log("write file OK"); }); console.log("do job success"); })