I’m trying to parse an NZB file (which is XML) and sum the bytes attributes. Sometimes it works perfectly and sometimes it returns zero, and I can’t figure out why. The NZB files have identical structure as far as I can tell.
private Int32 processNZB(string sFilename)
{
XDocument xFile = XDocument.Load(sFilename);
Int32 sum = xFile.Descendants("segment").Sum(x => (int)x.Attribute("bytes"));
sum = (int)(sum / 1024 / 1024); // bytes -> MB
return sum;
}
Source code and sample files can be found here: http://jonathanslaven.com/.for/.stackoverflow/
Is there an obvious reason this isn’t working? Is there a better way of doing this? Thanks for your help.
Perhaps the initial value of sum is less than 10242 bytes? As you are performing integer division, the result will be trucated, so anything less than 10242 bytes will return zero.
For instance, the example NZB file @ wikipedia would give 0 when run through your algorithm.
EDIT:
Upon inspection of the “bad” files (actually, it’s the “good” one that isn’t following the spec), the reason it’s not working is that the default namespace of the root element is
"http://www.newzbin.com/DTD/2003/nzb"meaning any child nodes will inherit this namespace.This means that your query
.Descendants("segment")returns no nodes. Attaching the correct namespace fixes the problem.The following shows how you might modify your code to read such a file.
As an aside, I’d avoid posting files that suggest involvement in contraband.