我正在嘗試獲取 XML 檔案的總校驗和,如下所示:
<?xml version="1.0"?>
<student_update date="2022-04-19" program="CA" checksum="20021682">
<transaction>
<program>CA</program>
<student_no>10010823</student_no>
<course_no>*</course_no>
<registration_no>216</registration_no>
<type>2</type>
<grade>90.4</grade>
<notes>Update Grade Test</notes>
</transaction>
<transaction>
<program>CA</program>
<student_no>10010859</student_no>
<course_no>M-50032</course_no>
<registration_no>*</registration_no>
<type>1</type>
<grade>*</grade>
<notes>Register Course Test</notes>
</transaction>
</student_update>
我想知道我是否以正確的方式進行此操作..請告訴我:
XDocument xDocument = XDocument.Load(inputFileName);
XElement root = xDocument.Element("student_update");
IEnumerable<XElement> studentnoElement = xDocument.Descendants().Where(x => x.Name == "student_no");
int checksum = studentnoElement.Sum(x => Int32.Parse(x.Value));
if (!root.Attribute("checksum").Value.Equals(checksum))
{
throw new Exception(String.Format("Incorrect checksum total " "for file {0}\n", inputFileName));
}
我遇到了一些錯誤,但未按預期彈出例外,我正在尋找有關如何糾正此問題的建議。謝謝!
uj5u.com熱心網友回復:
從checksum屬性的根元素中,您將獲得具有string型別的值。
您可以通過以下方式檢查:
Console.WriteLine(root.Attribute("checksum").Value.GetType());
Integer在比較兩個值之前,您必須先轉換為。
int rootCheckSum = Convert.ToInt32(root.Attribute("checksum").Value);
if (!rootCheckSum.Equals(checksum))
{
throw new Exception(String.Format("Incorrect checksum total " "for file {0}\n", inputFileName));
}
或者更喜歡安全地轉換為整數Int32.TryParse()
int rootCheckSum = Convert.ToInt32(root.Attribute("checksum").Value);
bool isInteger = Int32.TryParse(root.Attribute("checksum").Value, out int rootCheckSum);
if (!isInteger)
{
// Handle non-integer case
}
if (!rootCheckSum.Equals(checksum))
{
throw new Exception(String.Format("Incorrect checksum total " "for file {0}\n", inputFileName));
}
示例程式
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458731.html
上一篇:MVCC#中的多個復選框選擇
