XML (.NET 1.1) Performance Guidelines - Writing XML

From Guidance Share

Revision as of 04:49, 14 December 2007; JD (Talk | contribs)
(diff) ←Older revision | Current revision | Newer revision→ (diff)
Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, and Alex Mackman

Use XmlTextWriter

Using XmlTextWriter is the preferred way to write XML. The XmlTextWriter class creates XML in a forward-only cursor style. It also takes care of XML encoding, handling of special characters, adding quotes to attribute values, namespace declarations, and insertion of end tags. By performing these tasks, XmlTextWriter helps ensure the output is well-formed. The following code fragment shows how to use XmlTextWriter to create XML.

  static void WriteQuote(XmlWriter writer, string symbol, 
               double price, double change, long volume)
     writer.WriteAttributeString("Symbol", symbol);
     writer.WriteElementString("Price", XmlConvert.ToString(price));
     writer.WriteElementString("Change", XmlConvert.ToString(change));
     writer.WriteElementString("Volume", XmlConvert.ToString(volume));
  public static void Main(){
      XmlTextWriter writer = new XmlTextWriter(Console.Out);
      writer.Formatting = Formatting.Indented;
      WriteQuote(writer, "MSFT", 74.125, 5.89, 69020000);

The previous code produces the following output.

  <Stock Symbol="MSFT">
Personal tools