是否有更快的方法来检查 LINQ to XML 中的 XML 元素?
目前,我正在使用以下扩展方法来使用 LINQ to XML 检索元素的值。它使用 Any()
来查看是否有任何具有给定名称的元素,如果有,它只获取值。否则,它返回一个空字符串。此方法的主要用途是当我将 XML 解析为 C# 对象时,因此我不希望在元素不存在时出现任何问题。
我还有针对其他数据类型(如 bool、int 和 double)的其他扩展方法,以及一些用于将自定义字符串解析为枚举或布尔值的自定义扩展方法。我也有同样的方法来处理属性。
有更好的方法吗?
/// <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;
}
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.
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.
Is there a better way to do this?
/// <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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样:
换句话说,找到第一个元素或返回 null,然后调用字符串转换运算符(对于 null 输入,它将返回 null),如果所有这些的结果都是 null,则默认为空字符串。
您可以将其拆分出来,而不会损失任何效率 - 但最主要的是它只需要查找该元素一次。
How about:
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.