Download and view my resume (PDF)

Monday, February 8, 2010

C# LINQ-to-SQL Code to Generate XMLNS:XLINK Attributes

Here is an example of how to use the LINQ-to-SQL XML API to create an XLINK attribute. I provide this example because I could not find it anywhere else on the internet. My task was to write a translation wrapper for a WMS (Web Mapping Service) server. To conform to the WMS spec I had to end up with tags in this form:

<onlineresource xmlns:xlink="" xlink:href=""/">

Specifically I needed both the "xmlns:xlink" attribute and the "xlink:href" attribute. At first I tried to trick LINQ-to-SQL into giving me those attributes using .AddAttribute("xmlns:xlink", xlinkUrl), but that did not work (because the API does not allow that kind of cheating).

The final solution was short and easy, but it was not straightforward until I knew how to do it. This solution is now stable and works correctly. Here it is:

XNamespace xlinkNamespace = "";

XDocument doc = new XDocument(
new XElement("OnlineResource",
new XAttribute(XNamespace.Xmlns + "xlink", ""),
new XAttribute(xlinkNamespace + "href", "http://localhost:1558/GenericWMS/WMS.ashx")

No comments:

Post a Comment