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
};
}
}
}
The best resource for .NET Developers. This blog guides about .NET (C#.NET, ASP.NET, ASP.NET MVC, SQL Server, ADO.NET), AngularJS, JSON, HTML, JavaScript, jQuery, CSS, Bootstrap, DotNetNuke, and .NET interview questions. This blog teaches everything about the .NET. Here you can find bunch of tutorials, Tips and tricks, code samples and examples.
Wednesday, 11 December 2019
C# - Read XML File Using XMLReader
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment