是否有更快的方法来检查 LINQ to XML 中的 XML 元素并解析 int?
仅供参考,这与我的上一个问题非常相似: 是否有更快的方法来检查 LINQ to XML 中的 XML 元素并解析 bool?
目前我正在使用以下扩展我使用 LINQ to XML 检索元素的 int 值的方法。它使用 Any() 查看是否有任何具有给定名称的元素,如果有,它会解析 int 值。否则,它返回 0。
此方法的主要用途是当我将 XML 解析为 C# 对象时,因此我不希望在元素不存在时发生任何事情。我可以更改它来尝试解析,但现在我假设如果该元素存在,那么解析应该成功。
有更好的方法吗?
/// <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 int value of the child element if it exists, or 0 if it doesn't.</returns>
public static int GetIntFromChildElement(this XElement x, string elementName)
{
return x.Elements(elementName).Any() ? int.Parse(x.Element(elementName).Value) : 0;
}
FYI, This is very similar to my last question: Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?
Currently I'm using the following extension method that I made to retrieve the int 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 parses the value for an int. Otherwise, it returns 0.
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 could change it to try parse, but for now I'm assuming that if the element is there, then the parsing should succeed.
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 int value of the child element if it exists, or 0 if it doesn't.</returns>
public static int GetIntFromChildElement(this XElement x, string elementName)
{
return x.Elements(elementName).Any() ? int.Parse(x.Element(elementName).Value) : 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 Jon Skeet 对这个问题的原始字符串版本的回答,我想出了这个:
我不确定这在技术上是否更快......?
如果存在一个元素,它只对该元素进行一次检查,但如果该元素不存在,则它必须解析
"0"
字符串。Based on Jon Skeet's answer to the original string version of this question, I came up with this:
I'm not sure if that is technically faster though...?
If there is an element, it only does one check for the element, but if the element doesn't exist, then it has to parse the
"0"
string.