Let’s say you’ve been given a large XML file – Let’s say, it’s too large to be stored in memory, and it contains data that you want to show wihin an App. Perhaps you don’t want to package the XML file with your app, because perhaps it’s big, or perhaps you don’t want someone extracting all your data wholesale, if they decompile your app.

You don’t want to have the app download the XML file, since it’s huge, and is going to be slow to download, and once again, could allow someone who decompiles your app, the ability to copy all your data,  Instead, you want to have your app send search queries to your server, and have your server read the XML file in an efficient way, and return snippets in back to the App.

So, lets create an API in C# to do that, using ASP.NET

First off, you need a way to read an XML file node by node in C#, without reading the entire document into memory, as I said, in this example, imagine the XML file is too big to load into memory at once – or you don’t want to unduly use too much memory on your server.

Here’s a code snippet to do that;

private static IEnumerable<XElement> SimpleStreamAxis(string inputUrl,
string elementName)
using (var reader = XmlReader.Create(inputUrl))
while (reader.Read())
if (reader.NodeType != XmlNodeType.Element) continue;
if (reader.Name != elementName) continue;
var el = XNode.ReadFrom(reader) as XElement;
if (el != null)
yield return el;

Now, assuming I have my XML file in a folder called /Data and it’s called clubs.xml. The Node I want to iterate is called GolfClubDTO and the element I want to search on is called ClubCity – so here’s my code

var strSearch = Request.QueryString[“Search”];
if (string.IsNullOrEmpty(strSearch))
Response.Write(“Pass a Search Param!”);
var strXmlPath = Server.MapPath(“~/data/Clubs.xml”);
var xeClubs = SimpleStreamAxis(strXmlPath, “GolfClubDTO”);
var lClubs = new List<XElement>();
foreach (var xeClub in xeClubs)
// ClubCity
var xClubCity = xeClub.Elements().FirstOrDefault(c => c.Name.LocalName == “ClubCity”);
if (xClubCity != null)
var strClubCity = xClubCity.Value;
if (strClubCity.ToLower() == strSearch.ToLower())
var strJson = JsonConvert.SerializeObject(lClubs, Newtonsoft.Json.Formatting.Indented);
Response.ContentType = “application/json”;
Response.AddHeader(“Access-Control-Allow-Origin”, “*”);

Here I am also writing out the data with the mime type application/json and allowing CORS, to make life easier for my clients.




Source link
thanks you RSS link
( https://blog.dotnetframework.org/2019/01//-an-api-from-an-xml-file-in-c/)


Please enter your comment!
Please enter your name here