Question

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");
Was it helpful?

Solution

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

elem.Attributes().FirstOrDefault(a=>a.Name.LocalName == "from");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top