我有这种XML结构:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>My Work</name>
<Placemark>
<name>Main Building</name>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Office 1</name>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Document>
</kml>
这继续......
我需要为每个建筑物选择建筑物“名称”并将其存储在列表中。我写了这段代码:
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
namespace dsdsdsds
{
public class Building
{
public string BuildingName { get; set; }
}
class MainClass
{
public static void Main(string[] args)
{
List<Building> buildingNames =
(from e in XDocument.Load("buildings.kml").Root
.Elements("Document")
select new Building
{
BuildingName = (string)e.Element("name")
}).ToList();
foreach (var e in buildingNames)
{
Console.WriteLine(e);
}
}
}
}
然而,它似乎不想输出任何东西,我无法找出我出错的地方。有谁可以帮助我?
谢谢
答案 0 :(得分:6)
您忘记了xml中声明的命名空间:
var xdoc = XDocument.Load("buildings.kml");
XNamespace kml = "http://www.opengis.net/kml/2.2";
var buildings = xdoc.Root.Elements(kml + "Document")
.Select(d => new Building {
BuildingName = (string)d.Element(kml + "name")
}).ToList();
答案 1 :(得分:2)
XDocument xDocument = XDocument.Load("buildings.kml");
XNamespace xNameSpace = "http://www.opengis.net/kml/2.2";
var names = from o in xDocument.Descendants(xNameSpace+"name")
select o.Value;
我认为这是最简单的方法;不要忘记在查询元素之前添加命名空间。
答案 2 :(得分:1)
从我所看到的,你试图遍历“文档” - 元素并选择它们的名字。相反,您可能希望更进一步,进入Placemark -elements,即
XDocument.Load("buildings.kml").Element("Document").Elements("Placemark")
select new Building
{
BuildingName = e.Element("name").Value
}).ToList();