Hashtable To Xml - CSharp System.Xml

CSharp examples for System.Xml:XML DataSet

Description

Hashtable To Xml

Demo Code


using System.Xml;
using System;/* w w  w.ja  va2  s. co  m*/

public class Main{
        public static XmlDocument HashtableToXml(System.Collections.Hashtable ht)
      {
         XmlDocument doc = new XmlDocument();
         System.Xml.XmlNode node, subnode;
         node = doc.CreateElement("root");
         doc.AppendChild(node);

         System.Collections.IDictionaryEnumerator en = ht.GetEnumerator();
         while(en.MoveNext())
         {
            subnode = node.AppendChild(node.OwnerDocument.CreateElement(Convert.ToString(en.Key)));
            subnode.InnerText = Convert.ToString(en.Value);
         }

         return doc;
      }
        /// <summary>
        /// Unlike XmlNode.AppendChild(), this one works regardless of if they have the same OwnerDocument or not. Unless there's a Scheme
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="childNode"></param>
        public static void AppendChild(XmlNode parentNode, XmlNode childNode)
        {
            if (parentNode.OwnerDocument == childNode.OwnerDocument)
                parentNode.AppendChild(childNode);
            else
            {
                XmlNode newChildNode = parentNode.OwnerDocument.CreateNode(childNode.NodeType, childNode.Name, null);
                parentNode.AppendChild(newChildNode);
                if (childNode.InnerText.Length > 0)
                    newChildNode.InnerText = childNode.InnerText;

                foreach (XmlAttribute attribute in childNode.Attributes)
                {
                    CreateAndAddAttribute(newChildNode, attribute.Name, attribute.InnerText);
                }

                foreach (XmlNode node in childNode.ChildNodes)
                {
                    AppendChild(newChildNode, node);
                }
            }
        }
}

Related Tutorials