小编Rob*_*sen的帖子

LINQ - > XML处理不存在的元素节点

我正在使用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)

但是,一旦我偶然发现没有"概述"标签的条目,问题就会到来......如果元素"概述"不存在,有没有办法返回一个空字符串?

c# linq-to-xml

2
推荐指数
1
解决办法
2241
查看次数

标签 统计

c# ×1

linq-to-xml ×1