Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if XML contains element when using LINQ to XML?

Tags:

c#

xml

linq

Given this structure:

 <root>
     <user>
           <userName>user1</userName>
           <userImageLocation>/user1.png</userImageLocation>
     </user>
     <user>
           <userName>user2</userName>
     </user>
 </root>

public class User
{
    public string UserName {get; set; }
    public string UserImageLocation {get; set; }
}

I use the LINQ to XML to get data from the XML file, like this:

XDocument document = XDocument.Parse(xmlFile);
List<User> listOfUsers =  
(from user in document.Descendants("user")
 select new User {
    UserName = user.Element("userName"),
    UserImageLocation = user.Element("userImageLocation"),
 }
).ToList<User>();

My problem is that not all user element contains a userImageLocation, and when trying to read the userImageLocation, it throws an exception.

How can I check if an XML element exist, and if it exists, read it?

like image 295
eflles Avatar asked Nov 29 '10 08:11

eflles


2 Answers

Your current code won't compile, as you're trying to assign an XElement to a string property. My guess is that you're using the XElement.Value property to convert it to a string. Instead of that, use the explicit string conversion, which will return null if you call it "on" a null XElement reference:

XDocument document = XDocument.Parse(xmlFile);
List<User> listOfUsers =  
(from user in document.Descendants("user")
 select new User {
    UserName = (string) user.Element("userName"),
    UserImageLocation = (string) user.Element("userImageLocation"),
 }
).ToList<User>();

Note that this is one of those situations which is rather more readable using dot notation:

XDocument document = XDocument.Parse(xmlFile);
List<User> listOfUsers = document
    .Descendants("user")
    .Select(user => new User { 
         UserName = (string) user.Element("userName"),
         UserImageLocation = (string) user.Element("userImageLocation") })
    .ToList();
like image 119
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet


try below code

UserImageLocation = user.Element("userImageLocation")!=null?user.Element("userImageLocation").Value:string.Empty
like image 24
TalentTuner Avatar answered Nov 14 '22 23:11

TalentTuner