Thursday, October 16, 2008

use a specialized Xml writer when creating xml strings

avoid creating Xml streams by string manipulation (e.g. string s = "<Name First='" + firstName + "' Last='" + lastName + "'/>), since you get no reserved character escaping and will throw an error when certain input characters are processed.

in .NET 3.5, there are two good choices: XDocument (in System.Xml.LINQ) and XmlWriter (in System.Xml). XDocument is particularly powerful, since both it and XElement have param of objects constructors, which means you can specify all elements and each element’s attributes in one statement. it ends up looking very declarative:

XDocument xDoc = new XDocument(
new XElement("Name",
new XAttribute("First", firstName),
new XAttribute("Last", lastName)

string encodedXml = xDoc.ToString();

you can use XmlWriter to write directly to a Stream or to a StringBuilder:

StringBuilder sb = new StringBuilder();

using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true } ))
writer.WriteAttributeString("First", firstName);
writer.WriteAttributeString("Id", lastName);

string encodedXml = sb.ToString();

No comments: