I don't have a lot to say, but this is my little bit.

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="http://www.w3.org/1999/xlink" xlink:href="http://www.globe.gov/"/">

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 = "http://www.w3.org/1999/xlink";

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

No comments:

Post a Comment