代码之家  ›  专栏  ›  技术社区  ›  mayo0o

检查元素的总和

  •  0
  • mayo0o  · 技术社区  · 3 年前

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

    我遇到了一些错误,例外情况并没有像预期的那样出现,我正在寻找一些关于如何纠正这一点的建议。非常感谢。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Yong Shun    3 年前

    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