【问题标题】:Check sum total on an element检查元素的总和
【发布时间】:2022-10-18 09:24:52
【问题描述】:

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

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

【问题讨论】:

  • “我遇到了一些错误,但没有按预期弹出异常,我正在寻找有关如何纠正此问题的建议。”- 分享错误怎么样? ;-)
  • 好吧,没有显示错误,那是我的问题。我故意在我的 XML 文件中输入了不正确的“校验和”,并且我所做的异常没有弹出。 @斯特凡
  • 那么,它会做什么呢?例如:如果您使用调试器并检查 if 语句的参数会发生什么?他们的价值观是什么?投掷周围是否有 try/catch 块?是否有其他异常被抑制?
  • 没有尝试/捕捉,但我从下面的答案中意识到我的问题是什么。我感谢您的帮助!

标签: c# .net xml xml-parsing


【解决方案1】:

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}
", 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}
", inputFileName));
}

Sample Program

【讨论】:

  • 不错的收获....
  • 非常感谢..没有意识到我需要这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 2019-03-23
  • 1970-01-01
相关资源
最近更新 更多