我正在解析XML。我通常按照下面代码中显示的方式来解析它,这很简单问题是我不拥有要解析的XML,并且无法更改它。有时没有缩略图元素(没有标签),我得到了Exception
。
有没有办法保持这种简单性并检查元素是否存在?还是我必须先使用LINQ获取XElement
列表,然后对其进行检查并仅填充现有的对象属性?
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
XDocument dataDoc = XDocument.Load(new StringReader(e.Result));
var listitems = from noticia in dataDoc.Descendants("Noticia")
select new News()
{
id = noticia.Element("IdNoticia").Value,
published = noticia.Element("Data").Value,
title = noticia.Element("Titol").Value,
subtitle = noticia.Element("Subtitol").Value,
thumbnail = noticia.Element("Thumbnail").Value
};
itemList.ItemsSource = listitems;
}
最佳答案
[编辑] Jon Skeet's answer应该是可接受的答案。它更具可读性,更易于应用。 [/ edit]
创建这样的扩展方法:
public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null)
{
var foundEl = parentEl.Element(elementName);
if (foundEl != null)
{
return foundEl.Value;
}
return defaultValue;
}
然后,像这样更改您的代码:
select new News()
{
id = noticia.TryGetElementValue("IdNoticia"),
published = noticia.TryGetElementValue("Data"),
title = noticia.TryGetElementValue("Titol"),
subtitle = noticia.TryGetElementValue("Subtitol"),
thumbnail = noticia.TryGetElementValue("Thumbnail", "http://server/images/empty.png")
};
这种方法允许您通过隔离元素存在检查来保持干净的代码。它还允许您定义默认值,这可能会有所帮助