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 JSON 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,
using (var reader = XmlReader.Create(inputUrl))
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”];
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)
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”;
Here I am also writing out the data with the mime type application/json and allowing CORS, to make life easier for my clients.