Reputation: 13
I want to load a config.xml file in c# an split it in 4 different lists. The XML file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configs version="1.0" author="AP">
<config ver="9.7">
<start>00090[ABCDEF].*</start>
<lines>544</lines>
<configFile>cfg_9_7.xml</configFile>
</config>
<config ver="9.7_512">
<start>00090[1-9].*</start>
<lines>512</lines>
<configFile>cfg_9_7_v2_512.xml</configFile>
</config>
<config ver="9.7">
<start>00090[2-7].*</start>
<lines>256</lines>
<configFile>cfg_9_7_small.xml</configFile>
</config>
</Configs>
I need to split the version of a config (config ver="..."
), the start, lines and configFile
. All of the Lists can save Strings so i only need the values and the attribute. I want to make this with a Linq to XML because i think its a lot faster and smaller than my "Read all Lines and search for keywords" function:
var cfg = File.ReadAllLines(folder + keyCfg);
List<String> config = new List<String>(cfg);
Boolean keyFormatConfig = false;
for (int i = 0; i < config.Count; i++)
{
String line = config[i];
while (line.StartsWith(" ") || line.StartsWith("\t"))
{
line = line.Substring(1);
}
if (line.StartsWith("<config ver=\""))
{
keyFormatConfig = true;
}
if (line.StartsWith("</config>"))
{
keyFormatConfig = false;
}
if (keyFormatConfig)
{
if (line.StartsWith("<config ver=\""))
{
String[] name = line.Split('"');
if (name.Length >= 2)
{
Version.Add(name[1]);
}
}
else if (line.StartsWith("<start>"))
{
line = line.Substring(7);
if (line.Contains("<"))
{
String[] value = line.Split('<');
Start.Add(value[0]);
}
}
else if (line.StartsWith("<lines>"))
{
line = line.Substring(7);
if (line.Contains("<"))
{
String[] value = line.Split('<');
Lines.Add(value[0]);
}
}
else if (line.StartsWith("<configFile>"))
{
line = line.Substring(12);
if (line.Contains("<"))
{
String[] value = line.Split('<');
ConfigFile.Add(value[0]);
}
}
}
}
Sorry for my bad English :)
Upvotes: 1
Views: 1522
Reputation: 32481
You can use XDocument
like this:
XDocument doc = XDocument.Load(yourFile);
var configs = doc.Descendants("config").Select(i => new Config()
{
Version = i.Attribute("ver").Value,
Start = i.Element("start").Value,
Lines = i.Element("lines").Value,
ConfigFile = i.Element("configFile").Value,
}).ToList();
And here is the Config
class
public class Config
{
public string Start { get; set; }
public string Lines { get; set; } //Also you may want to use int
public string ConfigFile { get; set; }
public string Version { get; set; }
}
Upvotes: 2
Reputation: 3253
A simple LINQ:
void Main()
{
var configFile = @"c:\temp\so\config.xml";
var xdoc = XDocument.Load(configFile);
var configs = xdoc.Element("Configs").Elements("config");
foreach (var c in configs)
{
Console.WriteLine (c.Attribute("ver").Value);
Console.WriteLine ("Start {0}",c.Element("start").Value);
}
}
running this will produce
9.7
Start 00090[ABCDEF].*
9.7_512
Start 00090[1-9].*
9.7
Start 00090[2-7].*
Upvotes: 4