I am trying to get the checksum total of an XML file as seen below:
<?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>
I am wondering if I am going about this the right way.. please let me know:
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));
}
I am running into some errors with the exception not popping up as expected, I am looking for some advice on how to correct this. Thank you!
CodePudding user response:
From the root element of the checksum
attribute, you are getting the value with the string
type.
You can check with:
Console.WriteLine(root.Attribute("checksum").Value.GetType());
You have to convert to Integer
first before comparing both values.
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));
}
Or prefer safely convert to Integer with 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));
}