4

我有这个 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);
            }
        }
    }
}

但是,它似乎不想输出任何东西,我无法找出我哪里出错了。有人可以帮我吗?

谢谢

4

3 回答 3

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();
于 2013-01-24T12:26:53.520 回答
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;

我认为这是最简单的方法;不要忘记在查询元素之前添加命名空间。

于 2013-01-24T12:36:05.753 回答
1

据我所知,您正试图遍历“文档”-元素并选择它们的名称。相反,您可能想更进一步,进入 Placemark 元素,即。

XDocument.Load("buildings.kml").Element("Document").Elements("Placemark")
                    select new Building
                    {
                        BuildingName = e.Element("name").Value
                    }).ToList();
于 2013-01-24T12:26:09.977 回答