【发布时间】:2014-01-21 05:17:18
【问题描述】:
通过 XmlDocument,我想获得零件编号为“500300-B21”的所有数量的总和。我在 C# 中的代码是:-
XmlDocument xworkload = new XmlDocument();
private void BtnPnoCount_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".hpa"; // Default file extension
dlg.Filter = "Xml documents (.hpa)|*.hpa"; // Filter files by extension
var result = dlg.ShowDialog();
if (result == true)
{
xworkload.Load(dlg.FileName);
string xmlcontents = xworkload.InnerXml; // To get inner Xml
if (null != xworkload.DocumentElement.SelectSingleNode("Interview"))
{
if (xworkload.DocumentElement.SelectSingleNode("Interview/Rack")!= null)
{
var xpath = "//Item/partnumber";
XmlNodeList qtysum = xworkload.DocumentElement.SelectNodes(xpath);
int sum = 0;
foreach (XmlNode node in qtysum)
{
if (node.SelectSingleNode("partnumber").InnerText == "500300-B21")
{
sum += Int32.Parse(node.SelectSingleNode("quantity").InnerText);
}
MessageBox.Show("The the sum of quantities with P/No 500300-B21 is " + sum.ToString());
}
}
}
}
}
这会引发 NullReferenceException。我想用那个零件号得到数量的总和
【问题讨论】:
-
仅供参考,XmlDocument 是 .NET 的一部分,而不是 C# 的一部分
-
@JohnSaunders:谢谢,我已经更新了
标签: .net xml loops foreach nodes