使用 LINQ 从 XML 文件中选择元素
本文关键字:选择 元素 文件 XML LINQ 使用 | 更新日期: 2023-09-27 17:55:51
我有这个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();