views:

14

answers:

1

I am trying to build a XML document using the GML namespace and XML to LINQ.

My goal is an XElement with contents like this:

<gml:name>...</gml:name>

But I get the following:

<name xmlns="http://www.opengis.net/gml" />

The problem is that the gml: is missing from the element. Why is that?


My code is as follows:

XNamespace nsGML = "http://www.opengis.net/gml";
XElement item = new XElement(nsGML + "name");
+3  A: 

First of all this XML

<name xmlns="http://www.opengis.net/gml" />

is equivalent to this XML

<gml:name xmlns:gml="http://opengis.net/gml" />

And all XML consumers should treat it as same. That said you can achieve the second output like this:

XNamespace nsGML = "http://www.opengis.net/gml";
XElement item = new XElement(nsGML + "name",
                    new XAttribute(XNamespace.Xmlns + "gml", nsGML.NamespaceName));

If you don't specify the namespace declaration attribute LINQ to XML will pick a prefix automatically for you (in this case it uses the empty one). If you want to force usage of a specific prefix you need to provide the namespace declaration attribute.

Vitek Karas MSFT
**Vitek**: Thanks for your quick reply. The equivalency I concluded, but I do want the visual appearance too - and your suggestion works like a charm :)
Chau