I have the following code in C# and .net 3.5 that is working fine but need to know if this can be simplified may be using Linq or something else? Basically I am reading a xml file to get the column names. And then try to copy the columns and the sequence attribute in a dictionary object if “isactive attribute of the column is “true”. I use this dictionary object in other part of code. I loop through elements and then attributes and look for the columns that are active, if active I store the sequence and finally add the column and the sequence to the dictionary.
var doc = XDocument.Load("DataStructure.xml");
var cols = doc.XPathSelectElements("/datastructure/" + sPageName + "/columns");
Dictionary<string, int> columns = new Dictionary<string, int>();
bool bAddData = true;
int sSequence = 0;
foreach (var col in cols.Elements())
{
foreach (XAttribute at in col.Attributes())
{
if (at.Name.ToString().ToLower().Equals("isactive") && at.Value.ToString() != "true")
{
bAddData = false;
break;
}
bAddData = true;
if (at.Name.ToString().ToLower().Equals("sequence"))
{
sSequence = Convert.ToInt32(at.Value.ToString());
break;
}
}
if (bAddData)
{
columns.Add(col.Name.ToString(), sSequence);
}
}
I am sure this is pretty poor code but I would like to know how can I improve it. Here is the xml data file. I am ok if I need to restructure the xml to make this simple.
<?xml version="1.0" encoding="utf-8" ?>
<datastructure>
<MyPage>
<columns>
<number isactive="true" sequence="1" />
<curr_code isactive="true" sequence="2" />
<curr_desc isactive="true" sequence="3" />
<tradecurrvalue isactive="true" sequence="4" />
<selectcurrvalue isactive="true" sequence="5" />
</columns>
</MyPage>
</datastructure>
I think that this should do it:
Edit:
Out of curiosity I wanted to find out what could be done about the original code without using LINQ once I figured out what it acutally did and how to best use the methods in the
XElementclass, and I arrived at this: