NodeJS生成XML文件

基本示例

安装依赖

1
npm install xml2js

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const fs = require('fs');
const xml2js = require('xml2js');

// 定义要转换为 XML 的 JavaScript 对象
const data = {
gameList: {
game: [
{
path: './megaman.zip',
name: "L 洛克人-力量之战[LKRLLZZ]",
image: './media/images/Mega Man - The Power Battle_screenscraper_mix_arrm.png',
video: "./media/videos/mbombrd.mp4"
}
]
}
};

// 创建 XML 构建器实例
const builder = new xml2js.Builder();

// 将 JavaScript 对象转换为 XML 字符串
const xml = builder.buildObject(data);

// 写入文件
fs.writeFile('gamelist.xml', xml, 'utf8', (err) => {
if (err) {
console.error('写入文件时发生错误:', err);
} else {
console.log('XML 文件已成功生成: gamelist.xml');
}
});

文件遍历生成

根据文件夹下文件生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const fs = require('fs');
const xml2js = require('xml2js');
const path = require('path');

// 定义递归查找文件的函数
function findFilesInDirectory (dir, files = []) {
// 读取指定目录下的所有文件和文件夹
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
// 如果是文件夹,则递归调用函数继续查找
findFilesInDirectory(fullPath, files);
} else {
// 如果是文件,则获取相对路径并添加到结果数组中
const relativePath = path.relative(process.cwd(), fullPath);
files.push(relativePath);
}
}
return files;
}


// 定义要转换为 XML 的 JavaScript 对象
const data = {
gameList: {
game: [

]
}
};

let targetDirectory = "F:\\Roms\\SFC"
try {
// 调用函数查找文件
const foundFiles = findFilesInDirectory(targetDirectory);
// 打印找到的文件的相对路径
console.log('找到的文件的相对路径:');
foundFiles.forEach(file => {
let fileName = path.basename(file)
let filePath = file.replace(targetDirectory, ".")
console.log(fileName);
console.log(filePath);
data.gameList.game.push({
path: filePath,
name: fileName,
image: "",
video: ""
})
});
} catch (error) {
console.error('查找文件时出错:', error);
}

// 创建 XML 构建器实例
const builder = new xml2js.Builder();

// 将 JavaScript 对象转换为 XML 字符串
const xml = builder.buildObject(data);

let xmlPath = path.join(targetDirectory, "gamelist.xml")
// 写入文件
fs.writeFile(xmlPath, xml, 'utf8', (err) => {
if (err) {
console.error('写入文件时发生错误:', err);
} else {
console.log('XML 文件已成功生成: gamelist.xml');
}
});