检查元素是否存在解析XML时 [英] Check if an element exists when parsing XML
问题描述
我解析XML。我通常解析它显示我的代码的方式下面是简单的问题是,我没有自己,我解析XML,我无法改变它。有时候没有缩略图元素(没有标签),我得到一个例外
。
有没有办法保持这种简单性和检查元素存在?还是我得先用LINQ的的XElement
清单,然后检查并填充只现有对象的属性?
无效wc_DownloadStringCompleted(对象发件人,DownloadStringCompletedEventArgs E)
{
的XDocument dataDoc = XDocument.Load(新StringReader(e.Result));
变种时listItems从noticia在dataDoc.Descendants(Noticia)
=选择新的新闻()
{
ID = noticia.Element(IdNoticia)发表= noticia.Element(数据).value的,
,价值
标题= noticia.Element(Titol)。价值
字幕= noticia.Element(Subtitol ).value的,
缩略图= noticia.Element(缩略图)值
}。
itemList.ItemsSource = listItems中;
}
创建一个扩展方法如下
公共静态字符串TryGetElementValue(此的XElement parentEl,字符串的ElementName,字符串设置defaultValue = NULL)
{
VAR foundEl = parentEl.Element(的ElementName);
如果(foundEl!= NULL)
{
返回foundEl.Value;
}
返回设置defaultValue;
}
然后,改变你这样的代码:
选择新的新闻()
{
ID = noticia.TryGetElementValue(IdNoticia),
公布= noticia.TryGetElementValue (数据),
标题= noticia.TryGetElementValue(Titol),
字幕= noticia.TryGetElementValue(Subtitol),
缩略图= noticia.TryGetElementValue(缩略图, HTTP://server/images/empty.png)
};
这方法可以让你保持一个干净的代码隔离元素存在的检查。它还允许你定义一个默认值,这可能是有益的。
I'm parsing XML. I normally parse it the way I show in the code below which is straightforward The problem is that I don't own the XML I'm parsing and I can't change it. Sometimes there is no thumbnail element (there are no tags) and I get an Exception
.
Is there a way to maintain this simplicity and check if the element exists? Or do I have to get first an XElement
list with LINQ, to then check it and fill only the existing object properties?
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;
}
Create an extension method like this :
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;
}
then, change your code like this :
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")
};
This approach allows you to keep a clean code with isolating the check of element presence. It also allow you to define a default value, which can be helpful
这篇关于检查元素是否存在解析XML时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!