将XML文件转化成JSON文件

[MenuItem("ExportXmlLanguage/将ChinaData下的XML文件转成Json文件")]

public static void ReadFiles() {

string path = Application.dataPath + "/AlllanguageResources/ChinaData";

DirectoryInfo sourceFolder = new DirectoryInfo(path);

if (sourceFolder != null) {

FileInfo[] fileInfoArray = sourceFolder.GetFiles();       

foreach (FileInfo file in fileInfoArray) {

if (file.Name.EndsWith(".xml")) {

int index = file.Name.IndexOf('.');

ReadXmlFile(path + "/" + file.Name, file.Name.Substring(0, index));

}

}

EditorUtility.DisplayDialog("转换完成", "请在ChinaJsonData目录下查看Json文件", "OK");

}

}


private static void ReadXmlFile(string xmlPath, string fileName) {

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(xmlPath);

string json = JsonConvert.SerializeXmlNode(xmlDoc);

SaveJsonFile(json, fileName);

}


private static void SaveJsonFile(string json, string fileName) {

string path = Application.dataPath + "/AlllanguageResources/ChinaJsonData";

string filePath = path + "/" + fileName + ".txt";

if (!Directory.Exists(path)) {

Directory.CreateDirectory(path);

}

if (File.Exists(filePath)) {

File.Delete(filePath);

}

FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

fileStream.Position = fileStream.Length;

StreamWriter writer = new StreamWriter(fileStream);

writer.AutoFlush = true;

writer.WriteLine(json);

writer.Flush();

writer.Close();

fileStream.Close();

AssetDatabase.Refresh();

}

备注:路径需要根据项目实际情况分配。

你可能感兴趣的:(将XML文件转化成JSON文件)