Register
Sunday, February 05, 2012
 
 DBAs And ProgrammersBlog
  
News! Minimize
   
 
 Print   
 
Misc Blog Stuff Minimize
   
 
 Print   
 
The Reluctant DBA Minimize
 
 
 
 Print   
 
Reluctant DBA Minimize
   
 
  
 
Reluctant DBA Minimize
   
 
  
 
The Reluctant DBA Minimize
 
Nov10

Written by:CarpDeus
11/10/2008 2:12 PM 

I do a fair share of C# programming in my job, in addition to the database component. And I love using string.Format() to easily build strings. And I'm in the midst of a conversion project where I'm going to have a static chunk of XML that I'll need to use for every record getting converted, and string.Format comes to the rescue in an not so intuitive way. I'll build a string with the replacement tokens and use that string as the pattern for the format command. So it will look something like this:

StringBuilder XmlTemplate = new StringBuilder("<root><record>");
int qID = 0;
XmlTemplate.AppendFormat("<Question Id=\"{0}\">[{1}]</Question",78,qID++);
XmlTemplate.AppendFormat("<Question Id=\"{0}\">[{1}]</Question", 42, qID++);
XmlTemplate.AppendFormat("<Question Id=\"{0}\">[{1}]</Question", 999, qID++);
XmlTemplate.AppendFormat("<Question Id=\"{0}\">[{1}]</Question", 8675349, qID++);
XmlTemplate.Append("</record></root>");
XmlTemplate = XmlTemplate.Replace('[', '{').Replace(']', '}');

// while inside loop of conversion data
string XmlToProcess = string.Format(XmlTemplate.ToString(), "first", "second", "third", "fourth");
MessageBox.Show(XmlToProcess );

The only real downside to this is that I need to use square brackets around the qID value and then replace them but it's still an efficient solution for this particular problem.

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment  Cancel 
 
 
  
 
Privacy Statement | Terms Of Use Copyright 2001-2008 by ReluctantDBA.com