【问题标题】:Combining various xml elements into one collection using GML/C#/LINQ使用 GML/C#/LINQ 将各种 xml 元素组合到一个集合中
【发布时间】:2016-08-29 19:22:09
【问题描述】:

我正在尝试用 C# 读取 GML 文件。我想将所有返回的数据存储在一个对象中。到目前为止,我已经能够返回所有数据,但在 3 个单独的对象中:

XDocument doc = XDocument.Load(fileName);
XNamespace gml = "http://www.opengis.net/gml";

// Points
var points = doc.Descendants(gml + "Point")
              .Select(e => new
              {
                POSLIST = (string)e.Element(gml + "pos")
              });

// LineString
var lineStrings = doc.Descendants(gml + "LineString")
                  .Select(e => new
                  {
                      POSLIST = (string)e.Element(gml + "posList")
                  });

// Polygon
var polygons = doc.Descendants(gml + "LinearRing")
               .Select(e => new
               {
                   POSLIST = (string)e.Element(gml + "posList")
               });

我想创建一个对象,而不是创建 3 个单独的对象,如下所示:

var all = doc.Descendants(gml + "Point")
          doc.Descendants(gml + "LineString")
          doc.Descendants(gml + "LinearRing")....

但需要一些帮助。先谢谢了。

样本数据:

<gml:Point>
<gml:pos>1 2 3</gml:pos>
</gml:Point>
<gml:LineString>
<gml:posList>1 2 3</gml:posList>
</gml:LineString>
<gml:LinearRing>
<gml:posList>1 2 3</gml:posList>
</gml:LinearRing>

【问题讨论】:

  • Gilad,我添加了示例数据。谢谢。

标签: c# xml linq linq-to-xml gml


【解决方案1】:

你可以使用Concat:

XDocument doc = XDocument.Load(fileName);
XNamespace gml = "http://www.opengis.net/gml";
var all = doc.Descendants(gml + "Point")
             .Concat(doc.Descendants(gml + "LineString"))
             .Concat(doc.Descendants(gml + "LinearRing"));

为了将值作为内部元素,您可以执行以下操作:

XDocument doc = XDocument.Load("data.xml");
XNamespace gml = "http://www.opengis.net/gml";
var all = doc.Descendants(gml + "Point")
             .Select(e => new { Type = e.Name, Value = (string)e.Element(gml + "pos") })
             .Concat(doc.Descendants(gml + "LineString")
                        .Select(e => new { Type = e.Name, Value = (string)e.Element(gml + "posList") }))
             .Concat(doc.Descendants(gml + "LinearRing")
                        .Select(e => new { Type = e.Name, Value = (string)e.Element(gml + "posList") }));

【讨论】:

  • @Robert Smith - 检查一下
  • 谢谢吉拉德!如您在上面的示例中所见,如何为点选择“pos”,为 LineString/Polygons 选择“posList”?
  • @RobertSmith - 它现在能满足您的需要吗?
  • 完美,甚至比完美还要好,因为您添加了我需要的“Type = e.Name”!非常感谢!
  • 再次感谢,我去看看文档。
猜你喜欢
  • 1970-01-01
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2011-02-23
  • 2013-11-07
  • 2020-09-19
  • 1970-01-01
相关资源
最近更新 更多