XML Parser Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓XML Parser runs in O(n) time and O(n) space, in C# as in every other language.
- ✓System.Xml offers XmlReader for forward-only streaming, XDocument for the LINQ to XML tree API, and XmlDocument as the older DOM.
- ✓Use XDocument with LINQ for readable queries over documents that fit in memory, and XmlReader with an explicit XmlReaderSettings for anything untrusted or large.
- ✓The C# trap: The platform changed its default and the code did not. On .NET Framework, XmlDocument resolved external entities by default and was a standard external-entity sink; on .NET Core and .NET 5 and later, XmlReaderSettings.DtdProcessing defaults to Prohibit and XmlResolver defaults to null, so the modern platform is safe out of the box.
- ✓XmlReader is forward-only and allocates nothing for the structure, so it handles documents far larger than memory.
What XML Parser actually is
XML Parser in C#: what you actually reach for
C# implementation
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public static class Xml
{
/// <summary>Hardened reader settings. On .NET Core and later these are
/// already the defaults; set them explicitly so a port from .NET
/// Framework cannot silently inherit the old, unsafe behaviour.</summary>
private static readonly XmlReaderSettings Safe = new()
{
DtdProcessing = DtdProcessing.Prohibit, // no entities at all
XmlResolver = null, // resolve nothing externally
IgnoreComments = true,
IgnoreWhitespace = true,
};
public static IEnumerable<(string Id, string Total)> StreamOrders(string path)
{
using var reader = XmlReader.Create(path, Safe);
string? id = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "order")
id = reader.GetAttribute("id");
else if (reader.NodeType == XmlNodeType.Element && reader.Name == "total" && id is not null)
yield return (id, reader.ReadElementContentAsString());
}
}
/// <summary>Tree + LINQ. XDocument.Parse THROWS on malformed input,
/// unlike the browser DOMParser which returns an error document.</summary>
public static List<(string Id, decimal Total)> ReadOrders(string xml)
{
var doc = XDocument.Parse(xml);
var result = new List<(string, decimal)>();
foreach (var el in doc.Descendants("order"))
{
var id = (string?)el.Attribute("id");
var total = (decimal?)el.Element("total");
if (id is not null && total is not null)
result.Add((id, total.Value));
}
return result;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for XML Parser?
System.Xml offers XmlReader for forward-only streaming, XDocument for the LINQ to XML tree API, and XmlDocument as the older DOM. All three are in the framework.
What is the most common C# mistake when implementing XML Parser?
The platform changed its default and the code did not. On .NET Framework, XmlDocument resolved external entities by default and was a standard external-entity sink; on .NET Core and .NET 5 and later, XmlReaderSettings.DtdProcessing defaults to Prohibit and XmlResolver defaults to null, so the modern platform is safe out of the box. The residual danger is migrated code, which frequently carries an explicit XmlResolver assignment or a DtdProcessing.Parse that was added years ago to make something work and now re-opens the hole on a platform that had closed it. Grep for XmlResolver and DtdProcessing when porting. Unlike the browser DOMParser, XDocument.Parse throws on malformed input, so at least that failure is loud.
How does XML Parser actually perform in C#?
XmlReader is forward-only and allocates nothing for the structure, so it handles documents far larger than memory. XDocument materialises the whole tree with an object per node, which is convenient and expensive in exactly the way a DOM always is. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.