2012-10-10 19 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 在此先感謝! –