【问题标题】:Getting sub elements using LINQ and XML in C#在 C# 中使用 LINQ 和 XML 获取子元素
【发布时间】:2012-10-04 00:46:33
【问题描述】:

我刚开始在 c# 中使用 linq 查询,我正在努力获取我需要的所有数据。

基本上我使用 google earth kml 文件作为我的 xml 文件。

结构如下。

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
 <Document>
  <Placemark>
    <name>XXX</name>
    <description>XXX</description>
    <styleUrl>XXX</styleUrl>
    <Point>
       <coordinates>XXX</coordinates>
    </Point>
  </Placemark>
 </Document>
</kml>

使用我的代码,我可以获得第一级元素(名称、描述、styleurl),但无法正确获取我的语法以获取 Point 中的坐标元素。谁能指出我正确的方向?我正在努力解决的问题是 Coord = p.Element(ns + "Point").Element(ns + "coordinates").Value,这应该是什么?

XNamespace ns = "http://earth.google.com/kml/2.2";

var placemarks = xdoc.Descendants(ns + "Placemark")
                     .Select(p => new
                          {
                               Name = p.Element(ns + "name").Value,
                               Desc = p.Element(ns + "description").Value,
                               Coord = p.Element(ns + "Point")
                                        .Element(ns + "coordinates").Value  
                          }).ToList();

【问题讨论】:

    标签: c# xml linq kml


    【解决方案1】:
      var placemarks = xdoc.Descendants(ns + "Placemark")
                                .Select(p => new
                                {
                                    Name = p.Element(ns + "name").Value,
                                    Desc = p.Element(ns + "description").Value,
                                    Coord = p.Descendants(ns + "coordinates")
                                             .First().Value
                                })
                                .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多