Returns contents of an XmlNode in a string. - CSharp System.Xml

CSharp examples for System.Xml:XML Node

Description

Returns contents of an XmlNode in a string.

Demo Code

// All rights reserved.
using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;//from   w  w w .  ja v a  2  s.com

public class Main{
        #endregion

        #region Conversions to String
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns contents of an XmlNode in a string.
        /// </summary>
        /// <param name="node">The XmlNode whose contents will be read into a string.</param>
        /// <returns>Xml formatted string with contents of "node" parameter.</returns>
        /// -----------------------------------------------------------------------------
        public static string NodeToString(XmlNode node)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("");
            System.IO.StringWriter sw = new System.IO.StringWriter(sb);
            XmlTextWriter writer = new XmlTextWriter(sw);
            writer.Formatting = Formatting.Indented;
            if (node == null)
            {
                writer.WriteStartElement("Node_Empty");
            }
            else
            {
                writer.WriteStartElement(node.Name);

                //  Write any attributes 
                foreach (XmlAttribute attr in node.Attributes)
                {
                    writer.WriteAttributeString(attr.Name, attr.Value);
                }

                //  Write child nodes
                XmlNodeList nodes = node.SelectNodes("child::*");
                NodeNavigator nav = new NodeNavigator();
                if (nodes != null)
                {
                    foreach (XmlNode n in nodes)
                    {
                        nav.LoopThroughChildren(writer, n);
                    }
                }
            }

            writer.WriteEndElement();
            writer.Close();

            return sw.ToString();
        }
}

Related Tutorials