簡體   English   中英

使用LINQ從XML文件中選擇元素

[英]Selecting elements from XML file using LINQ

我有這個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);
            }
        }
    }
}

但是,它似乎不想輸出任何東西,我無法找出我出錯的地方。 誰能幫助我?

謝謝

您忘記了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();
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;

我認為這是最簡單的方法; 不要忘記在查詢元素之前添加命名空間。

從我所看到的,你試圖循​​環“文檔” - 元素並選擇他們的名字。 相反,你可能想要更進一步,進入地標 - 元素,即。

XDocument.Load("buildings.kml").Element("Document").Elements("Placemark")
                    select new Building
                    {
                        BuildingName = e.Element("name").Value
                    }).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM