我想使用LINQ在c#中解析这个xml。我输入了地标名称'RFA13'。 我想得到这个输入值的坐标节点。
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'>
<Document>
<name>EQDemo</name>
<description><![CDATA[]]></description>
<Folder>
<name>Untitled layer</name>
<Placemark>
<styleUrl>#line-000000-4</styleUrl>
<name>RFA13</name>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<tessellate>0</tessellate>
<coordinates>-97.77405023574829,30.27369885454351,0.0 -97.79602289199829,30.261244946171974,</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
<Folder>
<name>Untitled layer</name>
<Placemark>
<styleUrl>#line-000000-4</styleUrl>
<name>RFA14</name>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<tessellate>0</tessellate>
<coordinates>-97.76755392551422,30.284103698805,0.0 -97.77020126581192,30.279346144221726,0.0 -97.77405023574829,30.27369885454351,0.0</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
</Document>
</kml>
答案 0 :(得分:2)
您可以使用XDocument
和XPath:
var xDoc = XDocument.Load("Input.txt");
var coordinates = xDoc.XPathSelectElement(@"Document/Folder/Placemark[name = 'RFA13']/Polygon/outerBoundaryIs/LinearRing/coordinates");
您需要在文件顶部System.Xml.Linq
导入System.Xml.XPath
和using
。
答案 1 :(得分:0)
因此,您在kml
元素中声明了xml名称空间,然后您应该使用它来提供元素名称:
string name = "RFA13";
var xdoc = XDocument.Load(path_to_xml);
var ns = xdoc.Root.GetDefaultNamespace(); // get namespace
// find placemark element with name you provided
var placemark = xdoc.Descendants(ns + "Placemark")
.FirstOrDefault(p => (string)p.Element(ns + "name") == name);
if (placemark != null) // check if placemark found
{
// assume every placemark has coordinates
string coordinates = placemark.Descendants(ns + "coordinates")
.Select(c => (string)c)
.First();
}