恐怕你的代码工作正常。“temp”变量必须是字符串、空或空白。
我创建了一个XmlDocument(来自XDocument,抱歉。我认为它更容易使用),看起来像您的目标并运行代码。它运行良好,并给出适当的值:
var xDoc = new XDocument(
new XDeclaration("1.0", "UTF-8", "no"),
new XElement("root",
new XElement("account",
new XElement("systemInfo",
new XElement("dskInfo",
new XElement("dskInterface",
new XElement("size", 53999759360)))))));
var doc = new XmlDocument();
using (var xmlReader = xDoc.CreateReader())
{
doc.Load(xmlReader);
}
XmlNodeList accountList = doc.GetElementsByTagName("account");
foreach (XmlNode node in accountList)
{
XmlElement accountElement = (XmlElement)node;
foreach (XmlElement dskInterface in node.SelectNodes("systemInfo/dskInfo/dskInterface"))
{
String temp = (dskInterface["size"].InnerText).ToString();
long iasdas = Convert.ToInt64(temp) / 1024; // Error Happens here
}
}
编辑:
这里有一个更简单的方法来测试实际发生的情况:
Convert.ToInt64(null); // Doesn't crash
Convert.ToInt64(string.Empty); // Crashes
Convert.ToInt64(""); // Will crash if you comment the line above
Convert.ToInt64(" "); // Will crash if you comment the lines above