Skip to content

Instantly share code, notes, and snippets.

@ZXS66
Created July 23, 2022 01:51
Show Gist options
  • Save ZXS66/69c397ccc7db3687376edc1ff55acf09 to your computer and use it in GitHub Desktop.
Save ZXS66/69c397ccc7db3687376edc1ff55acf09 to your computer and use it in GitHub Desktop.
update angular xlf file
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
generateNewI18NFile();
return;
}
private static void generateNewI18NFile()
{
// step 1: extract all translations from history.xlf
// trans-unit@id, target
IDictionary<string, string> dict = new Dictionary<string, string>();
string[] allLines = File.ReadAllLines
(
"./history.xlf",
Encoding.UTF8 //Encoding.Default
);
string lastTransUnitId = string.Empty;
string lastTarget = string.Empty;
foreach (string line in allLines)
{
string line_trimed = line.Trim();
if (line_trimed.StartsWith("<trans-unit "))
{
int firstQuote = line_trimed.IndexOf("\""), secondQuote = line_trimed.IndexOf("\"", firstQuote + 1);
lastTransUnitId = line_trimed.Substring(firstQuote + 1, secondQuote - firstQuote - 1);
continue;
}
if (line_trimed.StartsWith("<target>"))
{
// all target values are inside one line
lastTarget = line;
dict.Add(lastTransUnitId, lastTarget);
}
}
// step 2: generate new translation file by appending target node
List<string> outputLines = new List<string>();
allLines = File.ReadAllLines("./now.xlf", Encoding.Default);
string[] prefixOfIgnoreLines = new string[]
{
"<?xml ",
"<xliff ",
"<file ",
"<body>",
"</body>",
"</file>",
"</xliff>"
};
foreach (string line in allLines)
{
outputLines.Add(line);
string line_trimed = line.Trim();
if (prefixOfIgnoreLines.Any(_ => line_trimed.StartsWith(_)))
continue;
if (line_trimed.StartsWith("<trans-unit "))
{
int firstQuote = line_trimed.IndexOf("\""), secondQuote = line_trimed.IndexOf("\"", firstQuote + 1);
lastTransUnitId = line_trimed.Substring(firstQuote + 1, secondQuote - firstQuote - 1);
continue;
}
if (line_trimed.EndsWith("</source>"))
{
lastTarget = dict.ContainsKey(lastTransUnitId) ? dict[lastTransUnitId] : string.Empty;
if (!string.IsNullOrEmpty(lastTarget))
{
outputLines.Add(lastTarget);
}
}
}
// step 3: write result to file
File.WriteAllLines("./output.xlf", outputLines);
//Console.WriteLine(string.Join(Environment.NewLine, outputLines));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment