检查元素的总和

Check sum total on an element

我正在尝试获取 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));
}

我 运行 遇到了一些错误,但没有按预期弹出异常,我正在寻找有关如何更正此问题的建议。谢谢!

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));
}

Sample Program