如何使用名称空间前缀创建XML?

时间:2012-09-14 07:37:53

标签: c# xml xsd

我应该如何用C#编写代码来创建像这样的

的xml文件
<ymaps:GeoObjectCollection>
    <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>

这个yandex的xml文件,它在http://maps.yandex.ru/schemas/ymaps/1.x/ymaps.xsd上有xsd文件

2 个答案:

答案 0 :(得分:0)

首先熟悉XMLXML NamespacesXML Schemas以及如何process XML data in .NET。掌握了基础知识后,使用XML Schema Definition Tool (Xsd.exe)从XSD生成类,并在应用程序中使用它。

答案 1 :(得分:0)

以下演示了如何使用LINQ to XML创建所需的XML。我创建了两个用于存储数据的类:GeoObjectPos

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>