Reputation: 19
I met a question that I can't get the attribute in the xml when the colon exists. For example, I want to get the value but it seems not working with my code. Any suggestions?
For Example:
Xml content:
<ext-link xlink:href="http://www.ncbi.nlm.nih.gov/books/NBK154461/" ext-link-type="uri" xmlns:xlink="http://www.w3.org/1999/xlink">http://www.ncbi.nlm.nih.gov/books/NBK154461/</ext-link>
My code:
foreach(XElement xeTmp in Elementlist)
{
string strValue = xeTmp.Attribute("xlink:href").Value;
}
Exception:
{"The ':' character, hexadecimal value 0x3A, cannot be included in a
name."}
please suggest how to fixed it.....
Upvotes: 1
Views: 2610
Reputation: 117016
First, the xlink:
prefix is the namespace prefix for the attribute. A namespace prefix has no intrinsic meaning, it's just a lookup for the namespace corresponding to the prefix, which must be declared by an xmlns:xlink="..."
attribute in scope, in this case:
xmlns:xlink="http://www.w3.org/1999/xlink"
Second, the XElement.Attribute(XName)
method actually takes an XName
argument. This class represents the combination of an XML namespace and name, thus allowing you to specify the attribute namespace and name to search for using XName.Get()
:
var strValue = (string)xeTmp.Attribute(XName.Get("href", "http://www.w3.org/1999/xlink"));
Or equivalently using implicit operators:
var strValue = (string)xeTmp.Attribute(((XNamespace)"http://www.w3.org/1999/xlink") + "href");
To loop through all attributes of an element, you can use XElement.Attributes()
.
Upvotes: 7