views:

434

answers:

1

Hi All,

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");
+2  A: 

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

elem.Attributes().FirstOrDefault(a=>a.Name.LocalName == "from");
yapiskan
sweet, that is perfect!!!
Jonathan C Dickinson
yes, I like it too! ;)
yapiskan
by the way, for completeness, it should be a=>a.Name.LocalName == "from".
Jonathan C Dickinson
+1. Query expressions are nice when they're doing complicated things, but when there are just one or two operations, the "dot notation" is indeed simpler.
Jon Skeet
@Jonathan - I've changed it.
yapiskan