문제

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");
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top