2012-10-10 17 views
3

可能重复:
How to set the default XML namespace for an XDocument使用C#和LINQ生成的飞行KML文件

我试图写在Asp.net C#的一段代码,以立即创建KML文件并将其存储在特定路径中。 当我想添加kml标记的xmlns =“http://earth.google.com/kml/2.2”属性时,该代码会给出错误(请参阅下文)。我尝试用另一个词替换xmlns,如“id”,它工作得很好。它与“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> 

回答

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

); 
+0

谢谢!它就像我想要的那样工作! :) :) –

+0

你介意回答我的其他问题: http://stackoverflow.com/questions/12846827/creating-dynamic-kml-file-using-linq-in-a-loop-in-asp-net -c-sharp 在此先感谢! –