LINQ:获取具有任何命名空间但特定名称的属性

发布于 2024-07-08 19:49:28 字数 872 浏览 5 评论 0原文

我需要能够从具有特定本地名称但任何名称空间的元素中获取单个特定属性(如果您熟悉 XMPP,您就会明白原因)。 除了编写我自己的(枚举器或单选)扩展方法之外,还有什么想法吗?

我有以下内容,但我根本不喜欢它:

        XAttribute from = (from c in elem.Attributes()
                           where c.Name.LocalName == "from"
                           select c).FirstOrDefault<XAttribute>();

        XAttribute to = (from c in elem.Attributes()
                         where c.Name.LocalName == "to"
                         select c).FirstOrDefault<XAttribute>();

编辑:想要类似的东西:

        string val = (string)elem.Attribute("{*}to");

解决方案:

        XAttribute from = elem.Attributes()
            .FirstOrDefault(a => a.Name.LocalName == "from");

        XAttribute to = elem.Attributes()
            .FirstOrDefault(a => a.Name.LocalName == "to");

I need to be able get a single specific attribute from an element with a specific local name but any namespace (if you are familiar with XMPP you will understand why). Apart from writing my own (enumerator or single select) extension methods, any ideas?

I have the following, but I don't like it at all:

        XAttribute from = (from c in elem.Attributes()
                           where c.Name.LocalName == "from"
                           select c).FirstOrDefault<XAttribute>();

        XAttribute to = (from c in elem.Attributes()
                         where c.Name.LocalName == "to"
                         select c).FirstOrDefault<XAttribute>();

edit: would like something like:

        string val = (string)elem.Attribute("{*}to");

solution:

        XAttribute from = elem.Attributes()
            .FirstOrDefault(a => a.Name.LocalName == "from");

        XAttribute to = elem.Attributes()
            .FirstOrDefault(a => a.Name.LocalName == "to");

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

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

发布评论

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

评论(1

凝望流年 2024-07-15 19:49:28

如果你不喜欢这种语法,你可以使用这个;

elem.Attributes().FirstOrDefault(a=>a.Name.LocalName == "from");

If you don't like the syntax, you can use this one;

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