Wednesday 11 December 2019

C# - Read XML File Using XMLReader

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace XmlProgramming
{
    internal class TagReader
    {
        public string XmlFilePath { get; }
        public string XmlElementName { get; }

        public TagReader(string xmlFilePath, string xmlElementName)
        {
            XmlFilePath = xmlFilePath;
            XmlElementName = xmlElementName;
        }

        /// <summary>
        /// Read tags from the given XML file.
        /// Func helpful in passing method to the XElement.
        /// If you want to do any other operations over the elements we can pass the function to this. 
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> Read<T>(Func<XElement,T> func)
        {
            using (FileStream fs = new FileStream(XmlFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (XmlReader reader = XmlReader.Create(fs, GetXmlSettings()))
                {
                    reader.MoveToContent();

                    // Parse the file and return each of the nodes.
                    while (!reader.EOF)
                    {
                        if (reader.NodeType == XmlNodeType.Element && reader.Name == XmlElementName)
                        {
                            if (XNode.ReadFrom(reader) is XElement el)
                                yield return func(el);
                        }
                        else
                            reader.Read();
                    }
                }
            }
        }

        /// <summary>
        /// Returns Xml Reader Settings
        /// </summary>
        /// <returns></returns>
        private static XmlReaderSettings GetXmlSettings()
        {
            return new XmlReaderSettings
            {
                IgnoreComments = true,
                IgnoreProcessingInstructions = true,
                IgnoreWhitespace = true,
                XmlResolver = null,
                DtdProcessing = DtdProcessing.Parse,
                CheckCharacters = false
            };
        }
    }
}

No comments: