我有一个问题,我的代码有时只能工作,我希望有更多专业知识的人能检查我做得不正确的地方。根据一些阅读,直接作为Descendants查询标记似乎是获取信息的最简单方法,但我开始意识到这可能不是最好的方法。
我的代码:
XDocument GMLfile = XDocument.Load(thefile.gml);
XNamespace gml = "http://www.opengis.net/gml";
//--------------------------------------------------
var coordquery = from coords in GMLfile.Descendants(gml + "coordinates") select coords.Value;
foreach (var coords in coordquery)
{
listBox1.Items.Add(coords);
}行为/问题:
它将正确解析一些文件,并获取所有水平对齐的坐标,但在其他文件中,它只会获取第一组逗号分隔的坐标,并在空格分隔符停止。
GML文件内容示例:
<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ogr.maptools.org/ zprocess.xsd"
xmlns:ogr="http://ogr.maptools.org/"
xmlns:gml="http://www.opengis.net/gml">
<gml:boundedBy>
<gml:Box>
<gml:coord><gml:X>-102.3542101578954</gml:X><gml:Y>48.27850492279583</gml:Y></gml:coord>
<gml:coord><gml:X>-100.6813690821913</gml:X><gml:Y>48.46080715637999</gml:Y></gml:coord>
</gml:Box>
</gml:boundedBy>
<gml:featureMember>
<ogr:Dak fid="F0">
<ogr:geometryProperty><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>-100.68704653821987,48.450386310687691 -100.68707054736575,48.450298060122066 -100.68710318142342,48.450211043099841 -100.68714430060783,48.450125632233721</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:Id>0</ogr:Id>
<ogr:Dist>500.00000000000</ogr:Dist>
</ogr:Dak>
</gml:featureMember>
</ogr:FeatureCollection>如果有人愿意定义一种更好的方法来实现这一点,或者详细说明在解析XML的各个部分时如何正确使用LINQ to XML,我将永远感激不尽!
致以亲切的问候,-GeekSmurf
发布于 2015-04-06 05:45:54
试试这个:
XNamespace gml = "http://www.opengis.net/gml";
var qry = xDoc.Root
.Elements(gml + "boundedBy")
.Elements(gml + "Box")
.Elements(gml + "coord")
.Select(a=>new
{
x=a.Element(gml + "X").Value,
y=a.Element(gml + "Y").Value
});以上查询返回:
x y
-102.3542101578954 48.27850492279583
-100.6813690821913 48.46080715637999 发布于 2015-04-06 23:23:18
如果您只需要坐标
XDocument xd = XDocument.Load("5.xml");
XNamespace gml = "http://www.opengis.net/gml";
var xy = xd.Root
.Descendants(gml + "coordinates")
.Select(y => y.Value.Split(' ').Select(z => z.Split(','))
.Select(z => new { X = z[0], Y = z[1] }).ToArray())
.Single();
Console.WriteLine(string.Join("\n",
xy.Select(z => string.Format("X:{0}\tY:{1}\t", z.X, z.Y))));输出:
X:-100.68704653821987 Y:48.450386310687691
X:-100.68707054736575 Y:48.450298060122066
X:-100.68710318142342 Y:48.450211043099841
X:-100.68714430060783 Y:48.450125632233721如果你需要得到其他东西,你需要展示如何看起来像一个结论。
https://stackoverflow.com/questions/29462322
复制相似问题