有没有更快的方法来检查LINQ to XML中的XML元素? [英] Is there a faster way to check for an XML Element in LINQ to XML?

查看:66
本文介绍了有没有更快的方法来检查LINQ to XML中的XML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用以下扩展方法,该方法是使用LINQ to XML检索元素的值的.它使用Any()来查看是否存在具有给定名称的元素,如果存在,则仅获取值.否则,它将返回一个空字符串.此方法的主要用途是用于将XML解析为C#对象时,因此,当元素不存在时,我不希望发生任何事情.

Currently I'm using the following extension method that I made to retrieve the values of elements using LINQ to XML. It uses Any() to see if there are any elements with the given name, and if there are, it just gets the value. Otherwise, it returns an empty string. The main use for this method is for when I'm parsing XML into C# objects, so I don't want anything blowing up when an element is not there.

对于其他数据类型,我还有其他扩展方法,例如bool,int和double,还有一些用于将自定义字符串解析为枚举或bool的自定义方法.我也有同样的方法来处理属性.

I have other extension methods for the other data type like bool, int and double, and some custom ones for parsing custom strings into enums or bools. I also have those same methods for working with attributes.

有更好的方法吗?

/// <summary>
/// If the parent element contains a element of the specified name, it returns the value of that element.
/// </summary>
/// <param name="x">The parent element.</param>
/// <param name="elementName">The name of the child element to check for.</param>
/// <returns>The value of the child element if it exists, or an empty string if it doesn't.</returns>
public static string GetStringFromChildElement(this XElement x, string elementName)
{
    return x.Elements(elementName).Any() ? x.Element(elementName).Value : string.Empty;
}

推荐答案

怎么样:

return ((string) x.Element(elementName)) ?? "";

换句话说,找到第一个元素或返回null,然后调用字符串转换运算符(对于null输入,它将返回null),如果所有结果均为null,则默认为空字符串.

In other words, find the first element or return null, then invoke the string conversion operator (which will return null for null input) and default to an empty string if the result of all of this is null.

您可以在不损失效率的情况下进行拆分-但主要是它只需要查找一次元素.

You could split that out without any loss of efficiency - but the main thing is it only needs to look for the element once.

这篇关于有没有更快的方法来检查LINQ to XML中的XML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆