如何检查是否XML使用LINQ to XML时,包含的元素? [英] How to check if XML contains element when using LINQ to XML?
问题描述
鉴于这种结构:
<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; }
}
我使用的LINQ to XML从XML文件中获取数据,如这样的:
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>();
我的问题是,并非所有的用户元素包含userImageLocation,并试图读取userImageLocation时,抛出一个异常。
My problem is that not all user element contains a userImageLocation, and when trying to read the userImageLocation, it throws an exception.
我如何检查是否一个XML元素存在,如果存在,读它?
How can I check if an XML element exist, and if it exists, read it?
推荐答案
您当前的代码将无法编译,因为你要分配的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();
这篇关于如何检查是否XML使用LINQ to XML时,包含的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!