使用C#和Linq动态生成kml文件

4

可能是重复问题:
如何为XDocument设置默认的XML命名空间

我正在尝试在Asp.net C#中编写一段代码,以便动态创建KML文件并将其存储在特定路径中。 当我想要添加kml标记的xmlns="http://earth.google.com/kml/2.2"属性时(如下所示),代码会出错。我尝试用另一个单词(如“id”)替换xmlns,这样就可以正常工作。这与单词“xmlns”有关吗?!对我来说很奇怪。

如果您了解问题所在,请提供解决方案...谢谢!

我的代码:

XDocument doc = new XDocument(
        new XDeclaration("1.0", "utf-8", ""),
        new XComment("This is comment by me"),
        new XElement("kml", new XAttribute("xmlns", "http://earth.google.com/kml/2.2"),
        new XElement("Document",
        new XElement("Name", "something"), new XElement("Placemark",
        new XAttribute("id", "1"),
        new XElement("title", "something"),
        new XElement("description", "something"),
        new XElement("LookAt",
        new XElement("Longitude", "49.69"),
        new XElement("Latitude", "32.345")), new XElement("Point", new XElement("Coordinates", "49.69,32.345,0"))))));
        doc.Save(Server.MapPath(@"~\App_Data\markers.xml"));

它给出的运行时错误:
引用块: 在同一起始元素标记内,前缀“”无法从“”重新定义为“http://earth.google.com/kml/2.2”。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误和代码中源自何处的更多信息。
异常详细信息:System.Xml.XmlException:在同一起始元素标记内,前缀“”无法从“”重新定义为“http://earth.google.com/kml/2.2”。
我想创建的kml文件:
<?xml version="1.0" encoding="utf-8"?>
<!--This is comment by me-->
<kml xmlns="http://earth.google.com/kml/2.2">
  <Document>
    <Name>something</Name>
    <Placemark id="1">
      <title>something</title>
      <description>something</description>
      <LookAt>
        <Longitude>49.69</Longitude>
        <Latitude>32.345</Latitude>
      </LookAt>
      <Point>
        <Coordinates>49.69,32.345,0</Coordinates>
      </Point>
    </Placemark>
  </Document>
</kml>
1个回答

2

首先定义命名空间

XNamespace n = "http://earth.google.com/kml/2.2";

new XElement(n+"kml")//just do n+ for each underlying elements

您的XML结构有误,应该像这样:
   XNamespace n = "http://earth.google.com/kml/2.2";
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", ""),
new XComment("This is comment by me"),
new XElement(n+"kml",
 new XElement(n+"Document",
        new XElement(n+"Name", "something"), new XElement(n+"Placemark",
        new XAttribute("id", "1"),
        new XElement(n+"title", "something"),
        new XElement(n+"description", "something"),
        new XElement(n+"LookAt",
        new XElement(n+"Longitude", "49.69"),
        new XElement(n+"Latitude", "32.345")), new XElement(n+"Point", new XElement(n+"Coordinates", "49.69,32.345,0")))))

);

你介意在这里回答我的另一个问题吗: http://stackoverflow.com/questions/12846827/creating-dynamic-kml-file-using-linq-in-a-loop-in-asp-net-c-sharp 提前感谢!! - Amin M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接