使用LINQ从XML文件选择元素 [英] Selecting elements from XML file using LINQ
本文介绍了使用LINQ从XML文件选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的XML结构:
I have this XML structure:
<?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>
这推移...
我需要选择建设名为他们每个人并存储这样的列表中。我写了这个代码:
I need to select the building "name" for each of them and store this inside a list. I have written this code:
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);
}
}
}
}
不过,它似乎并不想输出任何东西,我无法找到我要去的地方错了。谁能帮助我?
However, it doesn't seem to want to output anything and I cannot find out where I am going wrong. Could anyone help me?
感谢
推荐答案
您忘了命名空间在XML声明:
You forgot about namespace declared in your 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();
这篇关于使用LINQ从XML文件选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文