Linq To Xml Null 属性检查

发布于 2024-10-05 11:11:31 字数 1024 浏览 5 评论 0原文

<books>
   <book name="Christmas Cheer" price="10" />
   <book name="Holiday Season" price="12" />
   <book name="Eggnog Fun" price="5" special="Half Off" />
</books>

我想使用 linq 解析它,我很好奇其他人使用什么方法来处理特殊情况。我目前的处理方式是:

var books = from book in booksXml.Descendants("book")
                        let Name = book.Attribute("name") ?? new XAttribute("name", string.Empty)
                        let Price = book.Attribute("price") ?? new XAttribute("price", 0)
                        let Special = book.Attribute("special") ?? new XAttribute("special", string.Empty)
                        select new
                                   {
                                       Name = Name.Value,
                                       Price = Convert.ToInt32(Price.Value),
                                       Special = Special.Value
                                   };

我想知道是否有更好的方法来解决这个问题。

谢谢,

  • 贾里德
<books>
   <book name="Christmas Cheer" price="10" />
   <book name="Holiday Season" price="12" />
   <book name="Eggnog Fun" price="5" special="Half Off" />
</books>

I'd like to parse this using linq and I'm curious what methods other people use to handle special. My current way of working with this is:

var books = from book in booksXml.Descendants("book")
                        let Name = book.Attribute("name") ?? new XAttribute("name", string.Empty)
                        let Price = book.Attribute("price") ?? new XAttribute("price", 0)
                        let Special = book.Attribute("special") ?? new XAttribute("special", string.Empty)
                        select new
                                   {
                                       Name = Name.Value,
                                       Price = Convert.ToInt32(Price.Value),
                                       Special = Special.Value
                                   };

I am wondering if there are better ways to solve this.

Thanks,

  • Jared

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦毁影碎の 2024-10-12 11:11:31

您可以将该属性转换为字符串。如果不存在,您将得到 null 并且后续代码应检查 null,否则将直接返回该值。

试试这个:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = (string)book.Attribute("name"),
                Price = (string)book.Attribute("price"),
                Special = (string)book.Attribute("special")
            };

You can cast the attribute to a string. If it is absent you will get null and subsequent code should check for null, otherwise it will return the value directly.

Try this instead:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = (string)book.Attribute("name"),
                Price = (string)book.Attribute("price"),
                Special = (string)book.Attribute("special")
            };
年华零落成诗 2024-10-12 11:11:31

如何使用扩展方法来封装缺少的属性情况:

public static class XmlExtensions
{
    public static T AttributeValueOrDefault<T>(this XElement element, string attributeName, T defaultValue)
    {
        var attribute = element.Attribute(attributeName);
        if (attribute != null && attribute.Value != null)
        {
            return (T)Convert.ChangeType(attribute.Value, typeof(T));
        }

        return defaultValue;
    }
}

请注意,只有当 T 是字符串知道通过 IConvertible 转换为的类型时,这才有效。如果您想支持更一般的转换情况,您可能还需要寻找 TypeConverter。如果类型转换失败,这将引发异常。如果您希望这些情况也返回默认值,则需要执行额外的错误处理。

How about using an extension method to encapsulate the missing attribute cases:

public static class XmlExtensions
{
    public static T AttributeValueOrDefault<T>(this XElement element, string attributeName, T defaultValue)
    {
        var attribute = element.Attribute(attributeName);
        if (attribute != null && attribute.Value != null)
        {
            return (T)Convert.ChangeType(attribute.Value, typeof(T));
        }

        return defaultValue;
    }
}

Note that this will only work if T is a type to which string knows to convert via IConvertible. If you wanted to support more general conversion cases, you may need to look for a TypeConverter, as well. This will throw an exception if the type fails to convert. If you want those cases to return the default as well, you'll need to perform additional error handling.

审判长 2024-10-12 11:11:31

在 C# 6.0 中,您可以使用一元空条件运算符 ?.
在您的示例中应用它后,它看起来像这样:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = book.Attribute("name")?.Value ?? String.Empty,
                Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"),
                Special = book.Attribute("special")?.Value ?? String.Empty
            };

您可以阅读更多 此处部分标题为空条件运算符。

In C# 6.0 you can use monadic Null-conditional operator ?.
After applying it in your example it would look like this:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = book.Attribute("name")?.Value ?? String.Empty,
                Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"),
                Special = book.Attribute("special")?.Value ?? String.Empty
            };

You can read more here in part titled Null-conditional operators.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文