我正在开展一个项目,以从我们的交付数据库中生成一些 KML 数据。
我很高兴使用 LINQ 构建 KML 结构,但似乎当命名空间属性应用于节点时,我无法将数据输出到字符串。
这是我用来生成 KML 的代码:
// Create a new XDocument object
_xDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));
// Build internal kml document node
XElement document = CreateKmlDocumentNode();
if (document != null)
{
// Add data points to the kml document node
foreach (KmlData delivery in _deliveryData)
{
document.Add( CreatePlacemark(delivery) );
}
}
// Add the document node to the kml node
XElement kml = new XElement("kml",
document);
// ** Comment out this line and the output is generated **
kml.Add( new XAttribute("xmlns", @"http://earth.google.com/kml/2.2"));
// And finally add the kml node to the XDocument
_xDoc.Add( kml );
这是我用来生成字符串的代码:
string output;
using (var stringWriter = new StringWriter())
{
XmlWriterSettings xws = new XmlWriterSettings();
xws.NamespaceHandling = NamespaceHandling.OmitDuplicates;
xws.Indent = true;
using (var xmlTextWriter = XmlWriter.Create(stringWriter, xws))
{
// The Line below throws the exception when the namespace attribute is added
_xDoc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
output = stringWriter.GetStringBuilder().ToString();
}
}
return output;
生成的异常文本:
{“前缀 '' 不能在同一个起始元素标记中从 '' 重新定义为 'http://earth.google.com/kml/2.2'。”}
这是我希望数据看起来像的示例:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<name>Sample</name>
<description><![CDATA[]]></description>
<Style id="depot">
<IconStyle>
<Icon>
<href>http://maps.gstatic.com/mapfiles/ms2/micons/rangerstation.png</href>
</Icon>
</IconStyle>
</Style>
<Style id="pickupIcon">
<IconStyle>
<Icon>
<href>http://maps.gstatic.com/mapfiles/ms2/micons/truck.png</href>
</Icon>
</IconStyle>
</Style>
<Style id="letterIcon">
<IconStyle>
<Icon>
<href>http://maps.gstatic.com/mapfiles/ms2/micons/postoffice-us.png</href>
</Icon>
</IconStyle>
</Style>
<Placemark>
<name>Chester Depot</name>
<description><![CDATA[]]></description>
<styleUrl>#depot</styleUrl>
<Point>
<coordinates>-2.881701,53.197021,0.000000</coordinates>
</Point>
</Placemark>
<Placemark>
<name>15 Hankelow Close</name>
<description><![CDATA[<div><b><font size="4">Delivery Successful - 10:14am</font></b></div><div style="font-size:10pt"><b>Contact </b>Sam Spade</div><b style="font-size:10pt">Address </b><font size="2">15 Hankelow Close, Chester, Cheshire West and Chester CH2 2DZ, UK]]></description>
<styleUrl>#letterIcon</styleUrl>
<Point>
<coordinates>-2.889466,53.199226,0.000000</coordinates>
</Point>
</Placemark>
<Placemark>
<name>45 Victoria Rd</name>
<description><![CDATA[<div><b><font size="4">Pickup Successful - 1:24pm</font></b></div><div style="font-size:10pt"><b>Contact </b>Sam Spade</div><b style="font-size:10pt">Address </b><font size="2">Chester, Cheshire West and Chester CH2 2AX, UK]]></description>
<styleUrl>#pickupIcon</styleUrl>
<Point>
<coordinates>-2.892855,53.198498,0.000000</coordinates>
</Point>
</Placemark>
</Document>
</kml>