Last active
July 26, 2019 02:49
-
-
Save alialrahahleh/f30cf35633ff10be4ff7179c6128e595 to your computer and use it in GitHub Desktop.
usage $rdmd csvtoxml.d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import std.algorithm, std.stdio, std.string; | |
| import std.regex; | |
| import std.file; | |
| import std.conv; | |
| import std.typecons : Flag, Yes, No; | |
| import std.mmfile; | |
| import std.range: SortedRange; | |
| import std.getopt; | |
| import core.stdc.stdlib: exit; | |
| struct Options { | |
| string outFileName; | |
| string inFileName; | |
| string capture; | |
| string seprator = ","; | |
| string defValue = " "; | |
| }; | |
| void main(string[] args) | |
| { | |
| Options options; | |
| try { | |
| auto helpInformation = getopt( | |
| args, | |
| config.required, | |
| "inFile", "Input file (XML)", &options.inFileName, | |
| config.required, | |
| "outFile", "Output file (CSV)", &options.outFileName, | |
| config.required, | |
| "capture", "XML element to capture inside", &options.capture, | |
| "sep", "Seprator for csv output.", &options.seprator, | |
| "defValue", "Default value if element doesn't exists", &options.seprator, | |
| ); | |
| if (helpInformation.helpWanted) | |
| { | |
| defaultGetoptPrinter("Some information about the program.", helpInformation.options); | |
| exit(0); | |
| } | |
| } catch (GetOptException e) { | |
| writeln(e.message()); | |
| exit(-1); | |
| } | |
| auto eleRegex = ctRegex!(`^[\t\s]*<([^> ]+)`); | |
| auto valueRegex = ctRegex!(`^[\t\s]*<([^> ]+)>([^<]+)?`); | |
| auto outFile = File(options.outFileName, "w+"); | |
| auto capture = false; | |
| SortedRange!(string[], "a < b") keySorted; | |
| string[string] values; | |
| scope mmFile = new MmFile(options.inFileName); | |
| splitter( cast(string) mmFile[0..mmFile.length], '\n') | |
| .filter!"!a.empty" | |
| .map!(line => matchFirst(line, valueRegex)) | |
| .filter!("a.length > 1") | |
| .each!((x) { | |
| auto ele = to!string(x[1]); | |
| if (ele.cmp("/" ~ options.capture) == 0) { | |
| capture = false; | |
| string[] p; | |
| if (keySorted.length == 0) { | |
| keySorted = values.keys().sort(); | |
| outFile.write(keySorted.join(options.seprator) ~ "\n"); | |
| } | |
| foreach(l; keySorted) { | |
| if( l in values ) { | |
| p ~= values[l]; | |
| } else { | |
| p ~= options.defValue; | |
| } | |
| } | |
| outFile.write(p.join(options.seprator) ~ "\n"); | |
| values.clear(); | |
| } else if(ele.cmp(options.capture) == 0) { | |
| capture = true; | |
| } else if (capture && x.length > 2) { | |
| values[ele] = to!string(x[2]); | |
| } | |
| return Yes.each; | |
| }); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment