简体   繁体   中英

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.

Obviously based on some documents it may encounter some NullExceptions . (in line 5,6)

What way you recommend, how to change this piece of code to avoid using Try/Catch and not getting an exception?

            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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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