我正在使用Linq来解析xml文件,因为Linq占用的代码更少,但是我遇到了一个小问题,即一致的xml文件.我正在尝试从xml中解析出一个Series类,它基本上是这样设置的:
<series>
<showid>5</showid>
<showname>fringe</showname>
<overview>description of the tv-show fringe.</overview>
</series>
Run Code Online (Sandbox Code Playgroud)
这一切都很好,可以使用以下代码轻松解析:
var series = from serie in xdoc.Descendants ("Series")
select new TvShow()
{
ShowID = (string) serie.Element("seriesid").Value,
ShowName = (string) serie.Element ("SeriesName").Value,
ShowDescription = (string) serie.Element ("Overview").Value,
};
Run Code Online (Sandbox Code Playgroud)
但是,一旦我偶然发现没有"概述"标签的条目,问题就会到来......如果元素"概述"不存在,有没有办法返回一个空字符串?
绝对.不要使用该Value属性 - 请使用显式转换为字符串.这样,null如果元素不存在,您将获得,并且您可以使用null合并运算符:
var series = from serie in xdoc.Descendants("Series")
select new TvShow()
{
ShowID = (string) serie.Element("seriesid"),
ShowName = (string) serie.Element("SeriesName"),
ShowDescription = (string) serie.Element("Overview") ?? "",
};
Run Code Online (Sandbox Code Playgroud)
(显然你也可以为ShowName和ShowID做同样的事情.)
请注意,所有自定义转换都来自XAttribute并且XElement具有可为空的版本,例如转换为... int?而不是int......它们都以相同的方式工作,如果原始元素或属性为null,则返回空值.
| 归档时间: |
|
| 查看次数: |
2241 次 |
| 最近记录: |