Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

.Net - Use The Framework

4.82/5 (22 votes)
22 May 2010CPOL 40.7K  
Don't reinvent the wheel - use the one that's already on the cart.
I've found that there are many parts of the .Net framework that can be used "on the sly". For instance, there was a "Quick Answer" question posted today that presented this problem:

Given a string of configuration settings, like this (with more items than I'm showing here):

string text = "screen_fadetimeout=\"0\" font=\"Courier New\" fontsize=\"11\"


The user asked how to parse the string so he could change the settings in the string. Most of you may have already recognized this string for what it probably is - something from a XML file. There were a couple of responses to this question that suggested using the string.Split() method, or even Regex (wholly inappropriate IMHO), but there is an easier way, and the framework comes to the rescue.

Simply make the string into an acceptable XML format by added a name and the necessary brackets so that it takes on the look of an actual XML element, and then it's a simple matter to process the element instead of its string counterpart, like so:

// our original string
string text = "screen_fadetimeout=\"0\" font=\"Courier New\" fontsize=\"11\"";
// add our XML endcaps
text = string.Format("<TEST {0} />", text);
//Parse the string into an XML element
XElement element = XElement.Parse(text);
// change the value(s) we want to change
element.Attribute("screen_fadetimeout").Value = "5";
// and return our string to its original configuration
text = element.ToString().Replace("<TEST","").Replace("/>","").Trim();


My tip is to use the framework where possible instead of reinventing the wheel or doing things the hard way.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)