我已经问过一个类似的问题,当然,这个问题是不同的,我试过了。
我尝试使用 Linq 读取 XML 数据并解决了这个问题,但是,我需要选择多个值并将它们存储到字典中。我已经尝试过(评论是我的尝试)但我无法弄清楚并收到如下错误:
System.NullReferenceException: Object reference not set to an instance of an object at dsdsdsds.MainClass+c__AnonStorey0.<>m__0 (System.Xml.Linq.XElement datanum) [0x00000] in /Users/p/Projects/dsdsdsds/dsdsdsds/Main.cs:23
假设我的 XML 文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>My word place</name>
<Placemark>
<name>Main Building</name>
<id>1</id>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
现在我需要得到的是“name”和“id”,并将这些值放入字典中。
这是我的代码:
var xdoc = XDocument.Load ("buildings.kml");
XNamespace kml = "http://www.opengis.net/kml/2.2";
var dict = xdoc.Descendants(kml + "Placemark").ToDictionary (
datanum => datanum.Attribute(kml + "name").Value,
datanum => datanum.Attribute(kml + "id").Value );
/*.ToDictionary(e => e.Element("name").Value,
e => e.Descendants("id")
.Select (item => new Building
{
BuildingName = (string) e.Element(kml + "name").Value,
BuildingID = Convert.ToInt16(item.Element(kml + "id").Value)
}).ToList()
);
/*
/*var buildings = xdoc.Descendants (kml + "Placemark")
.Select((element, index) => new Building {
BuildingName = (string) element.Element(kml + "name"),
BuildingID = (int) element.Element(kml + "id")
});
*/
注意:我已尝试执行此操作三次,但是,得到相同/相似的错误消息。
最佳答案
name
和 id
是元素,不是属性。因此,您需要使用 Element()
而不是 Attribute()
:
var dict = xdoc.Descendants(kml + "Placemark")
.ToDictionary(datanum => datanum.Element(kml + "name").Value,
datanum => datanum.Element(kml + "id").Value);
如果 name
或 id
是可选标签,您可以使用以下代码来避免 NullReferenceException
:
var dict = doc.Descendants(kml + "Placemark")
.Select(x => new { name = (string)x.Element(kml + "name"),
id = (string)x.Element(kml + "id") })
.Where(x => x.name != null)
.ToDictionary(x => x.name, x => x.id);
请注意:这会忽略没有 name
标签的 Placemark
标签。只有 name
标签而没有 id
标签的 Placemark
标签仍被考虑在内。
顺便说一句:您的格式很好地掩盖了这一点,但是您在问题中提供的 XML 无效。格式正确,这变得很明显:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>My word place</name>
<Placemark>
<name>Main Building</name>
<id>1</id>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
关于c# - LINQ to Dictionary - 使用 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14502794/