SYSK 308: How to Add a Node at Runtime to XmlDataProvider

XmlDataProvider is great for data binding xml data.  But I’m yet to come across an example on how to on-the-fly add a node to a data source represented by an XmlDataProvider instance (e.g. if you use a grid control allowing a user to add a new row).


Below is an example of how one might achieve the desired effect:



// Create item

Trade item = new Trade();

item.Symbol = "MSFT";           

item.Quantity = 100;

item.TradeType = TradeType.Buy;

item.Price = 27.90;


// Serialize to xml

System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer(typeof(Trade));

System.Text.StringBuilder sb = new StringBuilder(512);


using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))


    xmls.Serialize(sw, item);



XmlDocument xml = new XmlDocument();



// TODO: Initialize your data instance (e.g. previously loaded xml

//       document, or Grid.DataSource, etc.)

XmlDataProvider data;


XmlNode newNode = data.Document.ImportNode(xml.ChildNodes[1], true);


// Append new node




. . .



[XmlType("trade", Namespace="YourCompany")]

public class Trade


    [XmlAttribute] public string ID = new Guid().ToString();

    [XmlAttribute] public DateTime Timestamp;

    [XmlAttribute] public TradeType TradeType;

    [XmlAttribute] public decimal Quantity;

    [XmlAttribute] public string Symbol;

    [XmlAttribute] public decimal Price;




[XmlType("tradeType", Namespace = "YourCompany")]

public enum TradeType


    [EnumMember] Undefined = 0,

    [EnumMember] Buy = 1,

    [EnumMember] Sell = 2,

    [EnumMember] BuyToOpen = 3,

    [EnumMember] BuyToClose = 4,

    [EnumMember] SellToOpen = 5,

    [EnumMember] SellToClose = 6,






Comments (5)

  1. Halu says:


Skip to main content