使用 C# 和 Linq 动态生成 kml 文件 [重复]

Posted

技术标签:

【中文标题】使用 C# 和 Linq 动态生成 kml 文件 [重复]【英文标题】:Generating a kml file on the fly using C# and Linq [duplicate] 【发布时间】:2012-10-10 13:41:54 【问题描述】:

可能重复:How to set the default XML namespace for an XDocument

我正在尝试在 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' 在同一个起始元素标记中。 说明:执行过程中发生未处理的异常 当前的网络请求。请查看堆栈跟踪以获取更多信息 有关错误的信息以及它在代码中的来源。

异常详细信息: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】:

先定义命名空间

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")))))

);

【讨论】:

谢谢!它就像我想要的那样工作! :) :) 你介意在这里回答我的另一个问题吗:***.com/questions/12846827/…提前谢谢!!

以上是关于使用 C# 和 Linq 动态生成 kml 文件 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

对动态生成的 KML 进行故障排除

c# linq 动态多条件查询语句的写法

动态生成collada文件

用于 kml 和文本文件的 UIActivityViewController

使用 Linq 表达式进行 C# 动态数据库过滤

C#中LINQ怎么生成下面那条SQL