且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否XML使用LINQ to XML时,包含的元素?

更新时间:2023-11-07 13:52:40

您当前的代码将无法编译,因为你要分配的XElement 来的字符串属性。我的猜测是,你正在使用的 XElement.Value 属性将其转换为字符串。取而代之的是,使用显式串转换,如果你把它叫做关于空的XElement 的参考,这将返回null:

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();