这里演示了如何使用 LINQ to XML 创建所需的 XML。我创建了两个类来存储数据:GeoObject
和Pos
:
var geoObjects = new[] {
new GeoObject {
Name = "Something",
Description = "Something",
Line = new[] {
new Pos { X = 50.588298M, Y = 55.145683M },
new Pos { X = 50.588290M, Y = 55.145678M },
new Pos { X = 50.588288M, Y = 55.145678M }
},
Style = "#customStyle1"
}
};
XML 是使用以下代码创建的:
XNamespace ymaps = "http://maps.yandex.ru/ymaps/1.x";
XNamespace gml = "http://www.opengis.net/gml";
var xElement = new XElement(
ymaps + "GeoObjectCollection",
new XAttribute(XNamespace.Xmlns + "ymaps", ymaps),
new XAttribute(XNamespace.Xmlns + "gml", gml),
new XElement(gml + "name", "Something"),
new XElement(gml + "featureMembers",
geoObjects.Select(
geoObject => new XElement(
ymaps + "GeoObject",
new XElement(gml + "name", geoObject.Name),
new XElement(gml + "description", geoObject.Description),
new XElement(gml + "LineString",
geoObject.Line.Select(
pos => new XElement(
gml + "pos",
String.Format(CultureInfo.InvariantCulture, "{0} {1}", pos.X, pos.Y)
)
)
),
new XElement(ymaps + "style", geoObject.Style)
)
)
)
);
如果你写出来,xElement
你会得到以下 XML:
<ymaps:GeoObjectCollection xmlns:ymaps="http://maps.yandex.ru/ymaps/1.x" xmlns:gml="http://www.opengis.net/gml">
<gml:name>Something</gml:name>
<gml:featureMembers>
<ymaps:GeoObject>
<gml:name>Something</gml:name>
<gml:description>Something</gml:description>
<gml:LineString>
<gml:pos>50.588298 55.145683</gml:pos>
<gml:pos>50.588290 55.145678</gml:pos>
<gml:pos>50.588288 55.145678</gml:pos>
</gml:LineString>
<ymaps:style>#customStyle1</ymaps:style>
</ymaps:GeoObject>
</gml:featureMembers>
</ymaps:GeoObjectCollection>