XML (.NET 1.1) Performance Guidelines - Writing XML

From Guidance Share

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.WriteStartElement("Stock");
     writer.WriteAttributeString("Symbol", symbol);
     writer.WriteElementString("Price", XmlConvert.ToString(price));
     writer.WriteElementString("Change", XmlConvert.ToString(change));
     writer.WriteElementString("Volume", XmlConvert.ToString(volume));
     writer.WriteEndElement();
  }
  public static void Main(){
      XmlTextWriter writer = new XmlTextWriter(Console.Out);
      writer.Formatting = Formatting.Indented;
      WriteQuote(writer, "MSFT", 74.125, 5.89, 69020000);
      writer.Close();
  }

The previous code produces the following output.


  <Stock Symbol="MSFT">
    <Price>74.125</Price>
    <Change>5.89</Change>
    <Volume>69020000</Volume>
  </Stock>
Personal tools