我正在解析XML.我通常按照我在下面的代码中显示的方式解析它很简单问题是我不拥有我正在解析的XML而且我无法更改它.有时没有缩略图元素(没有标签),我得到了一个Exception.
有没有办法保持这种简单性并检查元素是否存在?或者我必须首先获得XElementLINQ列表,然后检查它并仅填充现有的对象属性?
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;
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*e B 44
[编辑] Jon Skeet的答案应该是公认的答案.它更易读,更容易应用.[/编辑]
创建一个这样的扩展方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后,改变你的代码,如下所示:
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")
};
Run Code Online (Sandbox Code Playgroud)
这种方法允许您保持干净的代码,隔离元素存在的检查.它还允许您定义默认值,这可能会有所帮助
Jon*_*eet 34
而不是使用Value属性,如果你转换为字符串,你将只得到一个空引用:
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 = (string) noticia.Element("IdNoticia"),
published = (string) noticia.Element("Data"),
title = (string) noticia.Element("Titol"),
subtitle = (string) noticia.Element("Subtitol"),
thumbnail = (string) noticia.Element("Thumbnail")
};
itemList.ItemsSource = listitems;
}
Run Code Online (Sandbox Code Playgroud)
使用来自显式转换XElement到string,这通过返回一个空输出处理一个空的输入.这同样适用于所有的显式转换XAttribute和XElement可空类型,包括空值类型,例如int?-你只需要如果您正在使用要小心嵌套的元素.例如:
string text = (string) foo.Element("outer").Element("inner");
Run Code Online (Sandbox Code Playgroud)
如果inner缺少将提供空引用,但如果缺少则仍会抛出异常outer.
如果需要"默认"值,可以使用null合并运算符(??):
string text = (string) foo.Element("Text") ?? "Default value";
Run Code Online (Sandbox Code Playgroud)