对 XML 属性求和有时会返回零
我正在尝试解析 NZB 文件(XML)并对字节属性求和。有时它工作得很好,有时它返回零,我不明白为什么。据我所知,NZB 文件具有相同的结构。
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;
}
源代码和示例文件可以在这里找到: http://jonathanslaven.com/.for/.stackoverflow/
这不起作用有明显的原因吗?有更好的方法吗?感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许 sum 的初始值小于 10242 字节?当您执行整数除法时,结果将被截断,因此任何小于 10242 字节的内容都将返回零。
例如,示例 NZB 文件@wikipedia 在运行您的算法时将给出 0。
编辑:
在检查“坏”文件(实际上,这是不符合规范的“好”文件)时,它不起作用的原因是根元素的默认命名空间是
“http:// /www.newzbin.com/DTD/2003/nzb"
表示任何子节点都将继承此命名空间。这意味着您的查询
.Descendants("segment")
不返回任何节点。附加正确的命名空间可以解决问题。下面显示了如何修改代码来读取此类文件。
顺便说一句,我会避免发布暗示参与违禁品的文件。
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.
使用整数除法除以 1024 时,总和是否可能小到可以舍入为 0?
一个例子:
Is it possible that the sum is small enough to be rounded to 0 when dividing by 1024 using integer division?
An example:
如果你
改为
Does it work if you change
to