我正在解析 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")
};
这种方法允许您通过隔离元素存在的检查来保持干净的代码。它还允许您定义一个默认值,这很有用
关于c# - 解析 XML 时检查元素是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5336669/