From 6109715f767a03f69f53e8dd981c2c57003e955c Mon Sep 17 00:00:00 2001 From: Lilyltt <1806552019@qq.com> Date: Wed, 13 Mar 2024 11:26:16 +0800 Subject: [PATCH] Fix bug with selection,Change working ways --- srcxml2json/ObsoletedProgram.cs | 178 +++++++++++++++++++++++++ srcxml2json/Program.cs | 225 ++++++++++++++++---------------- srcxml2json/srcxml2json.csproj | 2 +- 3 files changed, 292 insertions(+), 113 deletions(-) create mode 100644 srcxml2json/ObsoletedProgram.cs diff --git a/srcxml2json/ObsoletedProgram.cs b/srcxml2json/ObsoletedProgram.cs new file mode 100644 index 0000000..f474d2d --- /dev/null +++ b/srcxml2json/ObsoletedProgram.cs @@ -0,0 +1,178 @@ +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text; +using System.Linq; + +class ObsoletedProgram +{ + static void Main1(string[] args) + { + var pattern1 = "^.*-srcxml2json.*$"; + var pattern2 = "^.*-json2srcxml.*$"; + var regex1 = new Regex(pattern1); + var regex2 = new Regex(pattern2); + if (regex1.IsMatch(args[0])) + { + // 调用src2json方法,将文件名作为参数传递 + if (Directory.Exists(args[1]) || File.Exists(args[1])) + { + var files = Directory.GetFiles(args[1], "*.srcxml"); + foreach (var file in files) + { + srcxml2json(args[1] + "\\" + Path.GetFileName(file)); + } + } + else + { + Console.WriteLine("Wrong Path!"); + } + } + else if (regex2.IsMatch(args[0])) + { + if (Directory.Exists(args[1]) || File.Exists(args[1])) + { + var files = Directory.GetFiles(args[1], "*.json"); + foreach (var file in files) + { + json2srcxml(args[1] + "\\", Path.GetFileName(file)); + } + } + else + { + Console.WriteLine("Wrong Path!"); + } + } + else + { + Console.WriteLine("Wrong Args! We only accept args like -srcxml2json or -srcxml2json!"); + } + } + + public static void srcxml2json(string fileName) + { + var matchContext = new List<(String name, string message)>(); + string patternName = "name=\"(.+?)\""; + string patternText = "text=\"(.+?)\""; + // 构建一个正则表达式对象 + Regex regexName = new Regex(patternName); + Regex regexText = new Regex(patternText); + // 读取文件内容 + using (StreamReader sr = new StreamReader(fileName)) + { + string line; + string lastLine = ""; + int linenum = 0; + while ((line = sr.ReadLine()) != null) + { + linenum++; + // 在每一行中查找匹配的内容 + Match matchText = regexText.Match(line); + if (matchText.Success) + { + Match matchName = regexName.Match(lastLine); + if (matchName.Success) + { + matchContext.Add((matchName.Groups[1].Value, matchText.Groups[1].Value)); + } + else + { + matchContext.Add(("", matchText.Groups[1].Value)); + } + } + + lastLine = line; + } + } + // 输出匹配的结果 + //foreach ((string name, string text) in matchContext) + //{ + // Console.WriteLine($"{name}:{text}"); + //} + //Console.WriteLine("Line-------"); + //foreach (int lineNumber in matchLineNum) + //{ + // Console.WriteLine($"Line{lineNumber}"); + //} + + //输出结果 + var resJson = "["; + foreach (var item in matchContext) + { + var itemJson = $"{{\"name\":\"{item.name}\",\"message\":\"{item.message.Replace(@"\", @"\\")}\"}}"; + resJson += itemJson + ","; + } + + if (matchContext.Count > 0) + { + resJson = resJson.Remove(resJson.Length - 1); + } + + resJson += "]"; + resJson = resJson.Replace(",", ",\n ").Replace("}", "\n}"); + //写入文件 + File.WriteAllText(fileName + ".json", resJson); + Console.WriteLine($"WriteFile {fileName} Done!"); + } + + public static void json2srcxml(string path, string fileName) + { + string json = File.ReadAllText(path+fileName, Encoding.UTF8); + List jsonList = JsonSerializer.Deserialize>(json); + string originName = fileName.Substring(0, fileName.LastIndexOf(".json")); + string patternName = @"name=""([^""]*)"""; + string patternText = @"text=""([^""]*)"""; + Regex regexName = new Regex(patternName); + Regex regexText = new Regex(patternText); + //读取文件 + using (StreamReader sr = new StreamReader(path+originName)) + { + string line; + string result = ""; + int count = 0; + while ((line = sr.ReadLine()) != null) + { + // 在每一行中查找匹配的内容 + Match matchName = regexName.Match(line); + if (matchName.Success) + { + string oldName = matchName.Groups[1].Value; + string newName = jsonList[count].name; + string replacedLine = regexName.Replace(line, "name=\"" + newName + "\""); + result += replacedLine + "\n"; + //text nextline + line = sr.ReadLine(); + Match matchText = regexText.Match(line); + string oldText = matchText.Groups[1].Value; + string newText = jsonList[count].message; + string replacedLine2 = regexText.Replace(line, "text=\"" + newText + "\""); + result += replacedLine2 + "\n"; + count++; + } + else + { + result += line+"\n"; + } + } + //写入文件 + File.WriteAllText(path+originName + ".after.srcxml", result.Replace(@"\\", @"\")); + Console.WriteLine($"WriteFile {originName}.after.srcxm Done!"); + } + } +} + +public class JsonFormat +{ + private string? _name; + + public string? name + { + get { return _name; } + set { _name = value; } + } + private string? _message; + public string? message + { + get { return _message; } + set { _message = value; } + } +} \ No newline at end of file diff --git a/srcxml2json/Program.cs b/srcxml2json/Program.cs index c51de03..51440e0 100644 --- a/srcxml2json/Program.cs +++ b/srcxml2json/Program.cs @@ -1,11 +1,15 @@ -using System.Text.RegularExpressions; -using System.Text.Json; using System.Text; -using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using System.Xml; + +namespace srcxml2json; -class Program +public class Program { - static void Main(string[] args) + private static void Main(string[] args) { var pattern1 = "^.*-srcxml2json.*$"; var pattern2 = "^.*-json2srcxml.*$"; @@ -13,13 +17,22 @@ static void Main(string[] args) var regex2 = new Regex(pattern2); if (regex1.IsMatch(args[0])) { - // 调用src2json方法,将文件名作为参数传递 if (Directory.Exists(args[1]) || File.Exists(args[1])) { var files = Directory.GetFiles(args[1], "*.srcxml"); foreach (var file in files) { - srcxml2json(args[1] + "\\" + Path.GetFileName(file)); + var msgs = XmlToList(file); + var json = JsonSerializer.Serialize(msgs, new JsonSerializerOptions() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }); + var dir = Path.GetDirectoryName(file); + var fileName = Path.GetFileNameWithoutExtension(file); + var jsonPath = Path.Combine(dir!, $"{fileName}.json"); + File.WriteAllText(jsonPath, json, Encoding.Unicode); + Console.WriteLine($"The file has been converted to json format! file path:{jsonPath}"); } } else @@ -34,7 +47,25 @@ static void Main(string[] args) var files = Directory.GetFiles(args[1], "*.json"); foreach (var file in files) { - json2srcxml(args[1] + "\\", Path.GetFileName(file)); + var xmlPath = Path.Combine(args[1], Path.GetFileNameWithoutExtension(file) + ".srcxml"); + var originMsgs = XmlToList(xmlPath); + var modifiedMsgs = JsonSerializer.Deserialize>(File.ReadAllText(file)); + if (modifiedMsgs is null) + { + Console.WriteLine($"The file is empty! file path:{file}"); + continue; + } + + if (originMsgs.Count != modifiedMsgs.Count) + { + Console.WriteLine( + $"The number of messages in the original file and the modified file is different! file path:{file}"); + continue; + } + + var xmlStr = ModifyXmlBack(xmlPath, modifiedMsgs); + File.WriteAllText(xmlPath + ".mod.srcxml", xmlStr, Encoding.Unicode); + Console.WriteLine($"The file has been modified! file path:{xmlPath}.mod.srcxml"); } } else @@ -48,131 +79,101 @@ static void Main(string[] args) } } - public static void srcxml2json(string fileName) + public static List XmlToList(string filePath) { - var matchContext = new List<(String name, string message)>(); - string patternName = "name=\"(.+?)\""; - string patternText = "text=\"(.+?)\""; - // 构建一个正则表达式对象 - Regex regexName = new Regex(patternName); - Regex regexText = new Regex(patternText); - // 读取文件内容 - using (StreamReader sr = new StreamReader(fileName)) + var msgs = new List(); + var doc = new XmlDocument(); + string xml; + using (var reader = new StreamReader(filePath)) { - string line; - string lastLine = ""; - int linenum = 0; - while ((line = sr.ReadLine()) != null) + xml = reader.ReadToEnd(); + } + + xml = xml.Replace("@", "_amp_"); + + doc.LoadXml(xml); + + var codeNode = doc.DocumentElement?.SelectNodes("/xscript/code"); + + if (codeNode is { Count: 0 }) + { + throw new InvalidDataException($"The file is empty! file path:{filePath}"); + } + + var nodes = codeNode![0]!.ChildNodes; + foreach (XmlNode node in nodes) + { + if (node.Name == "msg") { - linenum++; - // 在每一行中查找匹配的内容 - Match matchText = regexText.Match(line); - if (matchText.Success) + if (node.Attributes?["name"]?.Value is { } name && node.Attributes?["text"]?.Value is { } text) { - Match matchName = regexName.Match(lastLine); - if (matchName.Success) - { - matchContext.Add((matchName.Groups[1].Value, matchText.Groups[1].Value)); - } - else - { - matchContext.Add(("", matchText.Groups[1].Value)); - } + msgs.Add(new Msg(name, text)); } - - lastLine = line; } } - // 输出匹配的结果 - //foreach ((string name, string text) in matchContext) - //{ - // Console.WriteLine($"{name}:{text}"); - //} - //Console.WriteLine("Line-------"); - //foreach (int lineNumber in matchLineNum) - //{ - // Console.WriteLine($"Line{lineNumber}"); - //} - - //输出结果 - var resJson = "["; - foreach (var item in matchContext) + + return msgs; + } + + public static string ModifyXmlBack(string filePath, List msgs) + { + var doc = new XmlDocument(); + string xml; + using (var reader = new StreamReader(filePath)) { - var itemJson = $"{{\"name\":\"{item.name}\",\"message\":\"{item.message.Replace(@"\", @"\\")}\"}}"; - resJson += itemJson + ","; + xml = reader.ReadToEnd(); } - if (matchContext.Count > 0) + xml = xml.Replace("@", "_amp_"); + + doc.LoadXml(xml); + + var codeNode = doc.DocumentElement?.SelectNodes("/xscript/code"); + + if (codeNode is { Count: 0 }) { - resJson = resJson.Remove(resJson.Length - 1); + throw new InvalidDataException($"The file is empty! file path:{filePath}"); } - resJson += "]"; - resJson = resJson.Replace(",", ",\n ").Replace("}", "\n}"); - //写入文件 - File.WriteAllText(fileName + ".json", resJson); - Console.WriteLine($"WriteFile {fileName} Done!"); - } - - public static void json2srcxml(string path, string fileName) - { - string json = File.ReadAllText(path+fileName, Encoding.UTF8); - List jsonList = JsonSerializer.Deserialize>(json); - string originName = fileName.Substring(0, fileName.LastIndexOf(".json")); - string patternName = @"name=""([^""]*)"""; - string patternText = @"text=""([^""]*)"""; - Regex regexName = new Regex(patternName); - Regex regexText = new Regex(patternText); - //读取文件 - using (StreamReader sr = new StreamReader(path+originName)) + var nodes = codeNode![0]!.ChildNodes; + var index = 0; + foreach (XmlNode node in nodes) { - string line; - string result = ""; - int count = 0; - while ((line = sr.ReadLine()) != null) + if (node.Name == "msg") { - // 在每一行中查找匹配的内容 - Match matchName = regexName.Match(line); - if (matchName.Success) + if (node.Attributes?["name"]?.Value is not null && node.Attributes?["text"]?.Value is not null) { - string oldName = matchName.Groups[1].Value; - string newName = jsonList[count].name; - string replacedLine = regexName.Replace(line, "name=\"" + newName + "\""); - result += replacedLine + "\n"; - //text nextline - line = sr.ReadLine(); - Match matchText = regexText.Match(line); - string oldText = matchText.Groups[1].Value; - string newText = jsonList[count].message; - string replacedLine2 = regexText.Replace(line, "text=\"" + newText + "\""); - result += replacedLine2 + "\n"; - count++; - } - else - { - result += line+"\n"; + node.Attributes["name"]!.Value = msgs[index].Name; + node.Attributes["text"]!.Value = msgs[index].Text; + index++; } } - //写入文件 - File.WriteAllText(path+originName + ".after.srcxml", result.Replace(@"\\", @"\")); - Console.WriteLine($"WriteFile {originName}.after.srcxm Done!"); - } - } -} + } -public class JsonFormat -{ - private string? _name; + var xmlWriterSettings = new XmlWriterSettings + { + Indent = true, + IndentChars = " ", + NewLineChars = "\n", + NewLineHandling = NewLineHandling.Replace + }; + var stringWriter = new StringWriter(); + using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings)) + { + doc.WriteTo(xmlWriter); + } - public string? name - { - get { return _name; } - set { _name = value; } + var xmlStr = stringWriter.ToString(); + xmlStr = xmlStr.Replace("_amp_", "@"); + return xmlStr; } - private string? _message; - public string? message + + public record Msg(string Name, string Text) { - get { return _message; } - set { _message = value; } + [JsonPropertyName("name")] + public string Name { get; set; } = Name; + + [JsonPropertyName("text")] + public string Text { get; set; } = Text; } } \ No newline at end of file diff --git a/srcxml2json/srcxml2json.csproj b/srcxml2json/srcxml2json.csproj index 9627fe8..e0448aa 100644 --- a/srcxml2json/srcxml2json.csproj +++ b/srcxml2json/srcxml2json.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 enable enable