How to check if XML contains element when using LINQ to XML?
Given this structure:
<root>
<user>
<userName>user1</userName>
<userImageLocation>/user1.png</us开发者_JS百科erImageLocation>
</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?
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();
try below code
UserImageLocation = user.Element("userImageLocation")!=null?user.Element("userImageLocation").Value:string.Empty
精彩评论