Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 解析XML时检查元素是否存在_C#_Xml - Fatal编程技术网

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

C# 解析XML时检查元素是否存在,c#,xml,C#,Xml,我正在解析XML。我通常按照下面代码中显示的方式解析它,这很简单。问题是我不拥有我正在解析的XML,我无法更改它。有时没有缩略图元素(没有标记),我得到一个异常 有没有办法保持这种简单性并检查元素是否存在?或者我必须先用LINQ获取一个XElement列表,然后检查它并只填充现有的对象属性吗 void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { XDocument data

我正在解析XML。我通常按照下面代码中显示的方式解析它,这很简单。问题是我不拥有我正在解析的XML,我无法更改它。有时没有缩略图元素(没有标记),我得到一个
异常

有没有办法保持这种简单性并检查元素是否存在?或者我必须先用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;
}
[Edit]应该是可接受的答案。它更具可读性,更易于应用。[/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")
};
然后,按如下方式更改代码:

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")
};

这种方法允许您通过隔离元素存在的检查来保持代码的整洁。它还允许您定义一个默认值,这可能很有帮助

您可以使用
System.Xml.Serialization.XmlSerializer
将其从Xml反序列化为对象。然后,如果元素不存在,对象的属性将只获得它的默认值

请看这里: 还是新的道路

不使用
属性,如果强制转换为字符串,则只会得到一个空引用:

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;
}
它使用从
XElement
string
的显式转换,通过返回空输出来处理空输入。对于
XAttribute
XElement
上所有显式转换为可空类型(包括可空值类型,如
int?
)的情况也是如此-如果使用嵌套元素,只需小心。例如:

string text = (string) foo.Element("outer").Element("inner");
如果缺少
内部
,则将提供空引用,但如果缺少
外部
,则仍将引发异常

如果需要“默认”值,可以使用空合并运算符(
??
):


您可以使用以下代码:


string content=item.Element(“content”)==null?“”:item.Element(“Content”).Value

更好的用法:return foundEl=(parentEl.Element(elementName)?parentEl.Element(elementName)。值:defaultValue或return(foundEl!=null)?foundEl.Value:defaultValueBetter:使用XElement中已经存在的显式转换和默认值的null合并运算符…嗨,在搜索了扩展方法和null合并运算符之后,我实现了与您给我的示例中相同的转换,但在扩展方法中我有:return(parentEl.Element(elementName).Value??defaultValue);这是否正确?我一直在该行中获取NullReferenceException。谢谢您重现了相同的错误:if
parentEl.Element(elementName)
为null,您无法检索Value属性。请看示例。仅当元素存在时才调用.Value。好的,我明白了,对不起,我似乎不是很专注!我休息一下:)谢谢!