我正在尝试将XML文件解析为XDocument,并在节点丢失时遇到问题。我似乎无法使用null-coalescing运算符,因为我正在尝试将结果解析为列表,因此我得到编译时错误:运算符'??'不能从以下代码应用于'System.Collections.Generic.List'和'string'类型的操作数:
movies = (from item in doc.Root.Elements("item")
select new Movie
{
Title = (string)item.Element("title"),
IMDB_Id = ((string)item.Element("imdb_id")),
Actors = (from a in item.Element("actors").Elements("item")
select (string)a).ToList() ?? ""
通常有多个Actors节点可以读入我的列表:
<actor>
<item>Matt Damon</item>
<item>Ryan Gosling</item>
</actor
但是当没有actor节点时我得到一个错误,所以我试图将null结果转换为字符串(“”),但这不起作用,因为我得到上面的错误。那么我怎么能解析这个文件,知道每次读取文件时都不会出现所有节点?
答案 0 :(得分:0)
如果使用let
关键字并在不存在的情况下准备虚拟的空actors
元素,该怎么做?
movies = (from item in doc.Root.Elements("item")
let actorsElement = item.Element("actors") ?? new XElement("actors")
select new Movie
{
Title = (string)item.Element("title"),
IMDB_Id = ((string)item.Element("imdb_id")),
Actors = (from a in actorsElement.Elements("item")
select (string)a).ToList()
答案 1 :(得分:0)
你有几个问题:
ToList()
会返回一个空列表,而不是您期望的null
。Operator '??' cannot be applied to operands of type 'System.Collections.Generic.List' and 'string'
错误,因为如果列表不是null
,则会返回一个列表,否则将返回一个字符串。编译器不允许你这样做,因为C#是强类型的。您不能将列表分配给字符串,反之亦然。Actors
为空列表时,您知道何时没有actor。请使用Actors.Count() == 0
或!Actors.Any()
。我建议放弃可以为空的运算符,将其更改为:
Actors = (from a in item.Element("actors").Elements("item")
select a.ToString()).ToList();
可替换地:
Actors = item.Element("actors").Elements("item")
.Select(a => a.ToString()).ToList();