Creates XML document to a file. - CSharp System.Xml

CSharp examples for System.Xml:XML Document

Description

Creates XML document to a file.

Demo Code

// License:         MIT License (http://www.opensource.org/licenses/mit-license.php)
using System.IO;/*from w ww.  j a  v a  2  s .c  o  m*/
using System.Text;
using System.Xml;
using System;

public class Main{
        /// <summary>
        /// Creates XML document to a file.
        /// </summary>
        /// <param name="schemaName">Name of schema.</param>
        /// <param name="filename">Path to output file.</param>
        /// <returns>XML document.</returns>
        static public XmlDocument CreateXmlDocument(string schemaName, string filename)
        {
            // Ensure ".xml" is appended to document
            if (!filename.EndsWith(extension))
                filename += extension;

            // Create XML document, set schema, and get declaration
            XmlDocument document = new XmlDocument();
            XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, string.Empty);

            // Create writer and start XML file
            XmlWriter writer = XmlWriter.Create(filename, Settings);
            writer.WriteProcessingInstruction(declaration.Name, declaration.Value);
            writer.WriteStartElement(schemaName);
            writer.Close();

            // Load created document
            document.Load(filename);

            return document;
        }
        #endregion

        #region Static Methods

        /// <summary>
        /// Creates XML document.
        /// </summary>
        /// <param name="schemaName">Name of schema.</param>
        /// <returns>XML document.</returns>
        static public XmlDocument CreateXmlDocument(string schemaName)
        {
            // Create XML document, set schema, and get declaration
            XmlDocument document = new XmlDocument();
            XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, string.Empty);

            // Create writer and start XML file
            MemoryStream stream = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(stream, Settings);
            writer.WriteProcessingInstruction(declaration.Name, declaration.Value);
            writer.WriteStartElement(schemaName);
            writer.Close();

            // Load document from stream
            stream.Seek(0, SeekOrigin.Begin);
            document.Load(stream);

            return document;
        }
}

Related Tutorials