2008/05/16

Use XmlDocument to generate XML

This way is much simpler than XmlTextWriter:
public static String createItem(DataTable dt)
{
  XmlDocument XmlDoc = new XmlDocument();
  XmlDoc.LoadXml("");
  XmlElement XmlElem;

  foreach (DataRow dr in dt.Rows)
  {
    XmlElem = XmlDoc.CreateElement("customer");
    XmlElem.SetAttribute("Name", dr["custName"].ToString());
    XmlElem.SetAttribute("ID", dr["custID"].ToString());
    XmlElem.SetAttribute("Address", dr["address"].ToString());
    XmlElem.SetAttribute("ZipCode", dr["zip"].ToString());
    XmlElem.SetAttribute("Phone", dr["phone"].ToString());
    XmlElem.InnerText = "Kenny";

    XmlDoc.DocumentElement.AppendChild(XmlElem);
  }

  return XmlDoc.FirstChild.InnerXml;
}

No comments:

Post a Comment