c# - 解析 XML 时检查元素是否存在

标签 c# xml

我正在解析 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/

相关文章:

iphone - 如何在 XML (iOS) 中获取标签的一部分

c# - TCP 服务器/客户端的自定义消息框架协议(protocol)

c# - C#软件包Tyrrrz/YoutubeExplode对于YouTube html5视频返回错误403,但对于Flash视频则不返回错误403

xml - XPATH帮助选择元素

xml - 在 XSLT 中检查字符串是否为有效日期

xml - 如何在 SDL Tridion 中保留 xml 文件的处理指令?

c# - 未找到 System.ComponentModel.DataAnnotations

c# - 在 .NET 中创建加密安全随机 GUID

c# - 当 .Count() 大于零时从 .Select() 获取 NullReferenceException LINQ to XML

java - 从 SAX java XML 解析器,我如何知道 "DOCTYPE"关键字的大小写?