简体   繁体   English

在 XDocument 中搜索 XML 节点时避免 Try n Catch

[英]Avoid Try n Catch when searching for XML nodes in XDocument

Here is a method to check if some specific nodes exist or not in XDocument files.这是一种检查XDocument文件中是否存在某些特定节点的方法。

Obviously based on some documents it may encounter some NullExceptions .显然,根据某些文档,它可能会遇到一些NullExceptions (in line 5,6) (第 5,6 行)

What way you recommend, how to change this piece of code to avoid using Try/Catch and not getting an exception?您推荐什么方式,如何更改这段代码以避免使用 Try/Catch 而不会出现异常?

            var xContents = xDocument.Root.Descendants("Content");
            if (xContents.Any())
            {
                doesIncludeThat =
                   xContents.Any(e => e.HasAttributes && e.Name == "Content"
                            && e.Attribute("Include").Value == @"Happy New Year");
             ...}}}

Instead of using e.Attribute(name).Value which will give a NullReferenceException if the attribute is not present, you can do one of these things which both will return null in this case:而不是使用e.Attribute(name).Value如果属性不存在会给出 NullReferenceException ,您可以执行以下操作之一,在这种情况下两者都将返回 null :

e.Attribute(name)?.Value

or或者

(string)e.Attribute(name)

The latter makes use of one of the conversion (cast) operators defined in XAttribute, which also return null if the attribute does not exist.后者使用 XAttribute 中定义的转换(转换)运算符之一,如果该属性不存在,它也会返回 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM