简体   繁体   中英

Read the XML using Linq and check if the elements exist

I want to read the XML using linq and check if the element exists and gets it value.

For example if the element is like <Name /> then Im getting NullException. How to check if its value is null or not and also if exists in the XML in single statement.

You can use explicit conversions like this:-

string result = (string)x.Element("Name");

Update:

If element itself is not present then you can use C# Null Colaescing operator like this:-

string result = (string)x.Element("Name") ?? "Default Value";

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