linq to xml,处理空标签

发布于 2024-10-05 01:40:25 字数 194 浏览 7 评论 0原文

如果源 XML 包含数字或缺少标签,则以下链接语句可以正常工作。我遇到的问题是当标签为空或使用非数字值时。可以修改此声明来处理这些情况吗?

Convert.ToInt32((string)Data.Elements("groupBy").Elements("depth").FirstOrDefault() ?? "0")

The following link statement works fine if the source XML contains a number or if the tags are missing. The problem I have is when the tags are empty or if a non-numeric value is used. Can this statement be modified to handle these situations ?

Convert.ToInt32((string)Data.Elements("groupBy").Elements("depth").FirstOrDefault() ?? "0")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅唱ヾ落雨殇 2024-10-12 01:40:25

不知道用 LINQ 解决这个问题的方法,但如果你不能保证 XML 文档的内容,那么使用 int.TryParse() 会更容易吗?,例如

int result = 0;
int.TryParse((string)Data.Elements("groupBy").Elements("depth").FirstOrDefault(), out result);

Don't know of a way to solve this with LINQ but if you cannot guarantee the content of the XML document then would it be easier to just use int.TryParse()?, e.g.

int result = 0;
int.TryParse((string)Data.Elements("groupBy").Elements("depth").FirstOrDefault(), out result);
长不大的小祸害 2024-10-12 01:40:25

我会简单地做:

try
    int result = (int)Data.Elements("groupBy").Elements("depth").FirstOrDefault();
catch
{
    // handle
}

I would simply do:

try
    int result = (int)Data.Elements("groupBy").Elements("depth").FirstOrDefault();
catch
{
    // handle
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文