我从XML文件中获取值并将它们放在dataGridView
中。我成功地这样做了,但在我想操纵我从XML文件获得的数据后,它不起作用,我得到Input string was not in a correct format.
的错误。
我的目标是转换从XML文件中捕获的数据并将其除以1024. InnerText
不是一个我可以安全地转换为long的字符串吗?我应该添加更多代码才能使其正常工作吗?
在我的调试过程中,我打印出temp的值,值为53999759360,我也试过不把它变成ToString(),同样的错误
以下是我的代码的一部分:( size的值为“53999759360”)
XmlDocument doc = new XmlDocument();
string xmlFilePath = @"C:\xampp\htdocs\userInfo.xml";
doc.Load(xmlFilePath);
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
}
}
答案 0 :(得分:3)
我担心您的代码运行正常。必须是" temp"变量是string.Empty或空格。
我创建了一个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