Reputation: 18202
It is easy to find out value of Xdocument attribute but how do we find attribute with prefix/Namespace.
XML code
<label:label xlink:type="resource" xlink:label="something" xlink:lang="en" xlink:id="res_4">My value</label:label>
I am trying to read attribute value xlink:Id (where p is XElement)
p => p.Attribute("xlink:id").Value
Which doesn't work at all.
Upvotes: 3
Views: 3004
Reputation: 13022
Use the XName
class:
XName.Get("id", XLinkNamespaceName)
With XLinkNamespaceName
the namespace with the prefix xlink
.
To get the namespace from a prefix, you can use: XElement.GetNamespaceOfPrefix()
.
p => p.Attribute(p.GetNamespaceOfPrefix("xlink") + "id").Value
But I advise you not to work with prefixes in your C# code and use namespace instead. Indeed,
<myFile xmlns:myPrefix="http://www.tempUri.org/MyNamespace">
<something myPrefix:myAttribute="myValue" />
</myFile>
Is "functionally" equivalent to:
<myFile xmlns:dfgerge="http://www.tempUri.org/MyNamespace">
<something dfgerge:myAttribute="myValue" />
</myFile>
Upvotes: 2
Reputation: 89325
Given you have declaration of the namespace prefix somewhere in the XML :
xmlns:xlink="dummy.url"
You can use XNamespace
variable that point to above namespace URI to access an attribute in the namespace :
XNamespace xlink = "dummy.url";
.....
p => p.Attribute(xlink+"id").Value
//or simply cast the XAttribute to string
//to avoid exception when the attribute not found in p
p => (string)p.Attribute(xlink+"id")
Upvotes: 5