Search code examples
c#linqattributesxelement

C# XElement Get Attribute with a Namespace


I have a number of XElements, but their "href" attribute has a namespace. When I try to get it, it returns null.

<link xlink:href="The/href" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="a/location">A value</link>

I have tried:

XElement linkEl = doc.Root.Element("link");
string hrefValue = linkEl.Attribute("href").Value //null;

I have also tried adding the namespace to the "href" like "xlink:href" in Attribute(), but this results in an error. Anyone know how to perform this magic?


Solution

  • For your sample xml you can't find your element by using its Name it must be the LocalName of the element.

    To get element by LocalName here is the sample:

    var linkElement = doc.Root.Elements().Where(e => e.Name.LocalName == "link").FirstOrDefault();
    var linkAttribute = linkElement.Attributes().Where(a => a.Name.LocalName == "href").FirstOrDefault();
    var hrefValue = linkAttribute.Value;