RoboYak
RoboYak

Reputation: 1482

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?

Upvotes: 1

Views: 1255

Answers (2)

Li-Jyu Gao
Li-Jyu Gao

Reputation: 940

Try this one:

XDocument doc = XDocument.Parse(@"<link xlink:href=""The/href"" xmlns:xlink=""http://www.w3.org/1999/xlink"" xmlns=""a/location"">A value</link>");

XNamespace ab = "http://www.w3.org/1999/xlink";
string hrefValue = doc.Root.Attribute(ab + "href").Value;

Upvotes: 3

tontonsevilla
tontonsevilla

Reputation: 2809

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;

Upvotes: 2

Related Questions