Building a well-formed XML programmatically (C#)
This post is more of a reminder to self. I keep debating with myself as to how to create a well-formed XML programmatically in C#.
After some researching, and trying out various methods, that included the StringBuilder class amongst other funny ways to do the same, I settled upon the following style.
For every class that I write, I include a ToXml() method, that returns a string representation of the xml representation of the class.
1: public string ToXml()
2: {
3: TextWriter obj = new StringWriter();
4: XmlTextWriter xmlString = new XmlTextWriter(obj);
5:
6: xmlString.WriteStartElement("Client");
7: xmlString.WriteElementString("ID", ID.ToString());
8: xmlString.WriteElementString("Name",Name);
9: xmlString.WriteElementString("Url", Url);
10: xmlString.WriteElementString("Notes", Notes);
11: xmlString.WriteElementString("CurrentStatus", (Convert.ToInt32(_Status)).ToString());
12: xmlString.WriteElementString("CurrentUserID",CurrentUserID.ToString());
13:
14: xmlString.WriteEndElement();
15: xmlString.Close();
16: obj.Close();
17:
18: return Helper.ReplaceSpecialCharacters(obj.ToString());
19: }
Should something better come up, I shall update this post accordingly.
Technorati Tags:
C#
,
.NET
,
XML