How to work with XML?

Shonn Lyga
PoZeCode
Published in
2 min readNov 12, 2015

TL;DR — When you are asked what is the right way of working with an XML file, remember, there is no 1 right way!

Another good header for this post might have been “The test that stumped them all”.

Lately we’ve been interviewing developers for a senior dev position. One of the questions we ask almost every candidate is “how would you work with an XML file?”. A pretty big portion of them don’t bother to ask any additional questions like

- How big is the file?
— Would i need to search it?
— Would i need to manipulate the document?
— If so, what kind of manipulations?
— Would i need full back and forth traversal?

Different combinations of answers to this set of questions should involve a different approach to solve a particular problem.

Relevant to every developer

Every developer should be considering the technique based on the answers to the above questions. 2 main considerations you should contemplate is whether you should load the whole document in to memory or should you use some technique that will allow you to traverse the document in a stream-like manner loading only relatively small pieces in to memory.

.NET specific usage

So what are your options? When considering in-memory operations, then you should consider using XDocument or the somewhat older XmlDocument class. Both classes will load the whole document into memory and perform their operations there. They are easier to use than stream-based types and their code looks cleaner, but if your document is very large you might experience some lag in performance. Just imagine loading 10GB into memory just to find and read a single entry.

For a stream-like API you can use XmlTextReader/XmlTextWriter. The disadvantages of these types is the relatively complex API since it works on a lower level. The advantage is of course that you don’t have to load the whole thing into memory.

There are tons of information on the net about all these, so i won’t elaborate about it here. Google it :)

If you are angry, mad or just happy about this post and want to share it with me — leave a comment.

Alway Be Coding (ABC)
Shonn Lyga.

--

--