Skip to main content

ogc_gml/
lib.rs

1//! Parse and write [OGC GML 3.2](https://www.ogc.org/standards/gml) geometry
2//! elements to and from [`geo-types`] geometries.
3//!
4//! GML is the XML interchange format behind WFS servers and much
5//! government / INSPIRE open data. This crate is *sans-IO*: strings in,
6//! [`Geometry<f64>`](geo_types::Geometry) out, and back. There are no file
7//! handles, sockets or async runtime involved, so it drops equally well into a
8//! WFS client, an ETL job, or a WASM build.
9//!
10//! # Quick start
11//!
12//! ```
13//! use geo_types::Geometry;
14//! use ogc_gml::{parse_gml, write_gml};
15//!
16//! let xml = r#"<gml:Point xmlns:gml="http://www.opengis.net/gml/3.2"
17//!                srsName="urn:ogc:def:crs:EPSG::4326">
18//!                <gml:pos>51.5 -0.12</gml:pos>
19//!              </gml:Point>"#;
20//!
21//! let parsed = parse_gml(xml)?;
22//! assert_eq!(parsed.srs_name.as_deref(), Some("urn:ogc:def:crs:EPSG::4326"));
23//! match &parsed.geometry {
24//!     Geometry::Point(p) => assert_eq!((p.x(), p.y()), (51.5, -0.12)),
25//!     _ => panic!("expected point"),
26//! }
27//!
28//! // ...and back out again.
29//! let roundtrip = write_gml(&parsed.geometry, parsed.srs_name.as_deref());
30//! assert!(roundtrip.contains("<gml:pos>51.5 -0.12</gml:pos>"));
31//! # Ok::<(), ogc_gml::GmlError>(())
32//! ```
33//!
34//! # Supported geometries
35//!
36//! | GML element    | `geo-types` equivalent |
37//! |----------------|------------------------|
38//! | `Point`        | [`Point`]              |
39//! | `LineString`   | [`LineString`]         |
40//! | `Polygon`      | [`Polygon`]            |
41//! | `MultiPoint`   | [`MultiPoint`]         |
42//! | `MultiCurve`   | [`MultiLineString`]    |
43//! | `MultiSurface` | [`MultiPolygon`]       |
44//!
45//! Coordinates are read from either `pos` or `posList`. Namespace prefixes are
46//! ignored, so `<gml:Point>`, `<Point>` and `<ns0:Point>` all parse. Polygon
47//! interior rings (holes) survive both directions.
48//!
49//! Arcs, curves with non-linear interpolation, `Envelope` and
50//! `GeometryCollection` are out of scope for 0.1.
51//!
52//! # Behaviour notes
53//!
54//! - **Axis order is taken verbatim.** Ordinates land in `x`, `y` in the order
55//!   they appear in the document; the crate never reinterprets them based on
56//!   `srsName`. GML for `urn:ogc:def:crs:EPSG::4326` is conventionally
57//!   latitude-first, so the first ordinate becomes `x`. Swap it yourself if
58//!   you need lon/lat.
59//! - **No reprojection.** `srsName` is carried through as an opaque string.
60//! - **3D input is flattened.** With `srsDimension="3"` the third ordinate is
61//!   parsed and then discarded, since `geo-types` is strictly 2D.
62//! - **First geometry wins.** [`parse_gml`] returns the first supported
63//!   geometry element it meets, which lets you point it straight at a WFS
64//!   `featureMember` payload.
65//!
66//! # Errors
67//!
68//! Everything fallible returns [`GmlError`], which implements
69//! [`std::error::Error`] and so composes with `anyhow`, `thiserror` and the
70//! `?` operator:
71//!
72//! ```
73//! use ogc_gml::{parse_gml, GmlError};
74//!
75//! assert!(matches!(parse_gml("<featureMember/>"), Err(GmlError::NoGeometry)));
76//! assert!(matches!(
77//!     parse_gml("<Point><pos>north east</pos></Point>"),
78//!     Err(GmlError::BadNumber(_)),
79//! ));
80//! ```
81//!
82//! [`geo-types`]: https://docs.rs/geo-types
83
84#![deny(missing_docs)]
85#![deny(rustdoc::broken_intra_doc_links)]
86#![forbid(unsafe_code)]
87#![warn(missing_debug_implementations)]
88
89use geo_types::{
90    Coord, Geometry, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon,
91};
92use quick_xml::events::Event;
93use quick_xml::Reader;
94use std::fmt;
95
96/// A parsed GML geometry plus the CRS metadata that accompanied it.
97///
98/// Returned by [`parse_gml`]. The geometry itself is a plain
99/// [`geo_types::Geometry<f64>`], so it plugs directly into the wider `geo`
100/// ecosystem; `srs_name` and `srs_dimension` preserve the context that
101/// `geo-types` has nowhere to store.
102///
103/// ```
104/// use ogc_gml::parse_gml;
105///
106/// let parsed = parse_gml(
107///     r#"<Point srsName="EPSG:27700" srsDimension="3"><pos>530000 180000 15</pos></Point>"#,
108/// )?;
109///
110/// assert_eq!(parsed.srs_name.as_deref(), Some("EPSG:27700"));
111/// assert_eq!(parsed.srs_dimension, 3); // the Z ordinate was dropped
112/// # Ok::<(), ogc_gml::GmlError>(())
113/// ```
114#[derive(Clone, Debug, PartialEq)]
115pub struct GmlGeometry {
116    /// The geometry converted to `geo-types`.
117    pub geometry: Geometry<f64>,
118    /// Value of the `srsName` attribute, if present (e.g. an EPSG URN).
119    pub srs_name: Option<String>,
120    /// Coordinate dimension declared via `srsDimension` (defaults to 2).
121    /// For 3D input, the third ordinate is discarded during conversion.
122    pub srs_dimension: usize,
123}
124
125/// Errors produced while parsing GML.
126///
127/// Marked `#[non_exhaustive]`, so match arms should include a `_` catch-all;
128/// new variants may be added in a minor release without a breaking change.
129#[derive(Debug)]
130#[non_exhaustive]
131pub enum GmlError {
132    /// Underlying XML is malformed.
133    Xml(quick_xml::Error),
134    /// A coordinate ordinate failed to parse as `f64`.
135    BadNumber(String),
136    /// Coordinate count is not a multiple of the dimension, or a ring/line is
137    /// too short.
138    BadCoordinates(String),
139    /// The document contains no supported GML geometry element.
140    NoGeometry,
141    /// A structural expectation was violated (e.g. `Polygon` without exterior).
142    Structure(String),
143}
144
145impl fmt::Display for GmlError {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            GmlError::Xml(e) => write!(f, "malformed XML: {e}"),
149            GmlError::BadNumber(s) => write!(f, "invalid ordinate: {s:?}"),
150            GmlError::BadCoordinates(s) => write!(f, "invalid coordinates: {s}"),
151            GmlError::NoGeometry => write!(f, "no supported GML geometry element found"),
152            GmlError::Structure(s) => write!(f, "invalid GML structure: {s}"),
153        }
154    }
155}
156
157impl std::error::Error for GmlError {}
158
159impl From<quick_xml::Error> for GmlError {
160    fn from(e: quick_xml::Error) -> Self {
161        GmlError::Xml(e)
162    }
163}
164
165/// Strips a namespace prefix: `gml:Point` -> `Point`.
166fn local(name: &[u8]) -> &[u8] {
167    name.rsplit(|&b| b == b':').next().unwrap_or(name)
168}
169
170#[derive(Default, Debug)]
171struct PendingCoords {
172    text: String,
173}
174
175impl PendingCoords {
176    fn into_coords(self, dim: usize) -> Result<Vec<Coord<f64>>, GmlError> {
177        let nums: Result<Vec<f64>, _> = self
178            .text
179            .split_whitespace()
180            .map(|t| t.parse::<f64>().map_err(|_| GmlError::BadNumber(t.into())))
181            .collect();
182        let nums = nums?;
183        if nums.is_empty() || nums.len() % dim != 0 {
184            return Err(GmlError::BadCoordinates(format!(
185                "{} ordinates not divisible by dimension {dim}",
186                nums.len()
187            )));
188        }
189        Ok(nums
190            .chunks(dim)
191            .map(|c| Coord { x: c[0], y: c[1] })
192            .collect())
193    }
194}
195
196/// Parses the first supported GML geometry element found in `xml`.
197///
198/// Supported elements: `Point`, `LineString`, `Polygon`, `MultiPoint`,
199/// `MultiCurve`, `MultiSurface` — under any namespace prefix, or none at all.
200/// Coordinates may be given via `pos` or `posList`.
201///
202/// Because it returns on the *first* match, you can hand it a whole WFS
203/// response rather than pre-extracting the geometry element.
204///
205/// # Examples
206///
207/// A polygon with a hole; the interior ring is preserved:
208///
209/// ```
210/// use geo_types::Geometry;
211/// use ogc_gml::parse_gml;
212///
213/// let parsed = parse_gml(
214///     r#"<gml:Polygon xmlns:gml="http://www.opengis.net/gml/3.2">
215///          <gml:exterior><gml:LinearRing>
216///            <gml:posList>0 0 10 0 10 10 0 10 0 0</gml:posList>
217///          </gml:LinearRing></gml:exterior>
218///          <gml:interior><gml:LinearRing>
219///            <gml:posList>4 4 6 4 6 6 4 6 4 4</gml:posList>
220///          </gml:LinearRing></gml:interior>
221///        </gml:Polygon>"#,
222/// )?;
223///
224/// match parsed.geometry {
225///     Geometry::Polygon(p) => {
226///         assert_eq!(p.exterior().coords().count(), 5);
227///         assert_eq!(p.interiors().len(), 1);
228///     }
229///     _ => panic!("expected a polygon"),
230/// }
231/// # Ok::<(), ogc_gml::GmlError>(())
232/// ```
233///
234/// # Errors
235///
236/// Returns [`GmlError::NoGeometry`] if the document holds no supported
237/// geometry element, [`GmlError::Xml`] if the XML itself is malformed,
238/// [`GmlError::BadNumber`] if an ordinate is not a valid `f64`,
239/// [`GmlError::BadCoordinates`] if the ordinate count does not divide by the
240/// coordinate dimension (or a line is too short), and
241/// [`GmlError::Structure`] for structural violations such as a `Polygon`
242/// carrying no exterior ring.
243pub fn parse_gml(xml: &str) -> Result<GmlGeometry, GmlError> {
244    let mut reader = Reader::from_str(xml);
245    reader.trim_text(true);
246
247    let mut srs_name: Option<String> = None;
248    let mut srs_dimension: usize = 2;
249
250    // Stack of geometry containers being built.
251    #[derive(Debug)]
252    enum Node {
253        Point(Option<Coord<f64>>),
254        LineString(Option<Vec<Coord<f64>>>),
255        Polygon {
256            exterior: Option<Vec<Coord<f64>>>,
257            interiors: Vec<Vec<Coord<f64>>>,
258            in_interior: bool,
259        },
260        MultiPoint(Vec<Point<f64>>),
261        MultiCurve(Vec<LineString<f64>>),
262        MultiSurface(Vec<Polygon<f64>>),
263    }
264
265    let mut stack: Vec<Node> = Vec::new();
266    let mut pending: Option<PendingCoords> = None;
267    let mut buf = Vec::new();
268
269    fn finish(node: Node) -> Result<Geometry<f64>, GmlError> {
270        Ok(match node {
271            Node::Point(Some(c)) => Geometry::Point(Point::from(c)),
272            Node::Point(None) => return Err(GmlError::Structure("Point without pos".into())),
273            Node::LineString(Some(cs)) => {
274                if cs.len() < 2 {
275                    return Err(GmlError::BadCoordinates("LineString needs >= 2 points".into()));
276                }
277                Geometry::LineString(LineString::from(cs))
278            }
279            Node::LineString(None) => {
280                return Err(GmlError::Structure("LineString without posList".into()))
281            }
282            Node::Polygon { exterior, interiors, .. } => {
283                let ext = exterior
284                    .ok_or_else(|| GmlError::Structure("Polygon without exterior ring".into()))?;
285                Geometry::Polygon(Polygon::new(
286                    LineString::from(ext),
287                    interiors.into_iter().map(LineString::from).collect(),
288                ))
289            }
290            Node::MultiPoint(ps) => Geometry::MultiPoint(MultiPoint::new(ps)),
291            Node::MultiCurve(ls) => Geometry::MultiLineString(MultiLineString::new(ls)),
292            Node::MultiSurface(ps) => Geometry::MultiPolygon(MultiPolygon::new(ps)),
293        })
294    }
295
296    loop {
297        match reader.read_event_into(&mut buf)? {
298            Event::Start(e) => {
299                let name = e.name();
300                let tag = local(name.as_ref()).to_vec();
301                // Capture CRS metadata from the outermost geometry element.
302                if stack.is_empty()
303                    && matches!(
304                        tag.as_slice(),
305                        b"Point" | b"LineString" | b"Polygon" | b"MultiPoint" | b"MultiCurve"
306                            | b"MultiSurface"
307                    )
308                {
309                    for attr in e.attributes().flatten() {
310                        match local(attr.key.as_ref()) {
311                            b"srsName" => {
312                                srs_name =
313                                    Some(String::from_utf8_lossy(&attr.value).into_owned());
314                            }
315                            b"srsDimension" => {
316                                srs_dimension = String::from_utf8_lossy(&attr.value)
317                                    .parse()
318                                    .map_err(|_| {
319                                        GmlError::BadNumber("srsDimension".into())
320                                    })?;
321                            }
322                            _ => {}
323                        }
324                    }
325                }
326                match tag.as_slice() {
327                    b"Point" => stack.push(Node::Point(None)),
328                    b"LineString" => stack.push(Node::LineString(None)),
329                    b"Polygon" => stack.push(Node::Polygon {
330                        exterior: None,
331                        interiors: Vec::new(),
332                        in_interior: false,
333                    }),
334                    b"MultiPoint" => stack.push(Node::MultiPoint(Vec::new())),
335                    b"MultiCurve" => stack.push(Node::MultiCurve(Vec::new())),
336                    b"MultiSurface" => stack.push(Node::MultiSurface(Vec::new())),
337                    b"interior" => {
338                        if let Some(Node::Polygon { in_interior, .. }) = stack.last_mut() {
339                            *in_interior = true;
340                        }
341                    }
342                    b"exterior" => {
343                        if let Some(Node::Polygon { in_interior, .. }) = stack.last_mut() {
344                            *in_interior = false;
345                        }
346                    }
347                    b"pos" | b"posList" => pending = Some(PendingCoords::default()),
348                    _ => {} // pointMember, curveMember, LinearRing, etc: structural only
349                }
350            }
351            Event::Text(t) => {
352                if let Some(p) = pending.as_mut() {
353                    if !p.text.is_empty() {
354                        p.text.push(' ');
355                    }
356                    p.text.push_str(&t.unescape()?);
357                }
358            }
359            Event::End(e) => {
360                let name = e.name();
361                match local(name.as_ref()) {
362                    b"pos" | b"posList" => {
363                        let coords = pending
364                            .take()
365                            .ok_or_else(|| GmlError::Structure("dangling pos end".into()))?
366                            .into_coords(srs_dimension)?;
367                        match stack.last_mut() {
368                            Some(Node::Point(slot)) => *slot = coords.first().copied(),
369                            Some(Node::LineString(slot)) => *slot = Some(coords),
370                            Some(Node::Polygon {
371                                exterior,
372                                interiors,
373                                in_interior,
374                            }) => {
375                                if *in_interior {
376                                    interiors.push(coords);
377                                } else {
378                                    *exterior = Some(coords);
379                                }
380                            }
381                            _ => {
382                                return Err(GmlError::Structure(
383                                    "coordinates outside a geometry".into(),
384                                ))
385                            }
386                        }
387                    }
388                    tag @ (b"Point" | b"LineString" | b"Polygon" | b"MultiPoint"
389                    | b"MultiCurve" | b"MultiSurface") => {
390                        let node = stack
391                            .pop()
392                            .ok_or_else(|| GmlError::Structure("unbalanced end tag".into()))?;
393                        let geom = finish(node)?;
394                        match stack.last_mut() {
395                            None => {
396                                return Ok(GmlGeometry {
397                                    geometry: geom,
398                                    srs_name,
399                                    srs_dimension,
400                                });
401                            }
402                            Some(Node::MultiPoint(v)) => {
403                                if let Geometry::Point(p) = geom {
404                                    v.push(p);
405                                }
406                            }
407                            Some(Node::MultiCurve(v)) => {
408                                if let Geometry::LineString(l) = geom {
409                                    v.push(l);
410                                }
411                            }
412                            Some(Node::MultiSurface(v)) => {
413                                if let Geometry::Polygon(p) = geom {
414                                    v.push(p);
415                                }
416                            }
417                            Some(_) => {
418                                return Err(GmlError::Structure(format!(
419                                    "unexpected nested {}",
420                                    String::from_utf8_lossy(tag)
421                                )))
422                            }
423                        }
424                    }
425                    _ => {}
426                }
427            }
428            Event::Eof => return Err(GmlError::NoGeometry),
429            _ => {}
430        }
431        buf.clear();
432    }
433}
434
435fn fmt_coords(cs: &LineString<f64>) -> String {
436    cs.coords()
437        .map(|c| format!("{} {}", c.x, c.y))
438        .collect::<Vec<_>>()
439        .join(" ")
440}
441
442/// Serializes a [`geo-types`] geometry to a GML 3.2 fragment using the `gml:`
443/// prefix.
444///
445/// The root element carries the GML 3.2 namespace declaration; pass
446/// `srs_name` to also emit an `srsName` attribute on it. The output is a
447/// fragment, not a document — there is no XML declaration — so it can be
448/// embedded directly in a larger WFS request.
449///
450/// Ordinates are written in `x y` order, exactly as stored, mirroring the
451/// verbatim axis handling of [`parse_gml`].
452///
453/// Geometry variants outside the supported set (notably
454/// [`Geometry::GeometryCollection`],
455/// [`Rect`](geo_types::Rect), [`Triangle`](geo_types::Triangle) and
456/// [`Line`](geo_types::Line)) render as an XML comment rather than failing, so
457/// a partial pipeline never panics mid-serialization.
458///
459/// # Examples
460///
461/// ```
462/// use geo_types::{Geometry, LineString};
463/// use ogc_gml::write_gml;
464///
465/// let line = Geometry::LineString(LineString::from(vec![(0., 0.), (1., 1.), (2., 0.)]));
466/// let xml = write_gml(&line, Some("EPSG:4326"));
467///
468/// assert!(xml.starts_with("<gml:LineString"));
469/// assert!(xml.contains(r#"srsName="EPSG:4326""#));
470/// assert!(xml.contains("<gml:posList>0 0 1 1 2 0</gml:posList>"));
471/// ```
472///
473/// Omitting the CRS leaves the attribute off entirely:
474///
475/// ```
476/// use geo_types::{Geometry, Point};
477/// use ogc_gml::write_gml;
478///
479/// let xml = write_gml(&Geometry::Point(Point::new(1.0, 2.0)), None);
480/// assert!(!xml.contains("srsName"));
481/// ```
482///
483/// [`geo-types`]: https://docs.rs/geo-types
484#[must_use]
485pub fn write_gml(geometry: &Geometry<f64>, srs_name: Option<&str>) -> String {
486    let srs = srs_name
487        .map(|s| format!(" srsName=\"{s}\""))
488        .unwrap_or_default();
489    let ns = " xmlns:gml=\"http://www.opengis.net/gml/3.2\"";
490    match geometry {
491        Geometry::Point(p) => format!(
492            "<gml:Point{ns}{srs}><gml:pos>{} {}</gml:pos></gml:Point>",
493            p.x(),
494            p.y()
495        ),
496        Geometry::LineString(l) => format!(
497            "<gml:LineString{ns}{srs}><gml:posList>{}</gml:posList></gml:LineString>",
498            fmt_coords(l)
499        ),
500        Geometry::Polygon(p) => {
501            let mut s = format!(
502                "<gml:Polygon{ns}{srs}><gml:exterior><gml:LinearRing><gml:posList>{}</gml:posList></gml:LinearRing></gml:exterior>",
503                fmt_coords(p.exterior())
504            );
505            for ring in p.interiors() {
506                s.push_str(&format!(
507                    "<gml:interior><gml:LinearRing><gml:posList>{}</gml:posList></gml:LinearRing></gml:interior>",
508                    fmt_coords(ring)
509                ));
510            }
511            s.push_str("</gml:Polygon>");
512            s
513        }
514        Geometry::MultiPoint(mp) => {
515            let members: String = mp
516                .iter()
517                .map(|p| {
518                    format!(
519                        "<gml:pointMember><gml:Point><gml:pos>{} {}</gml:pos></gml:Point></gml:pointMember>",
520                        p.x(),
521                        p.y()
522                    )
523                })
524                .collect();
525            format!("<gml:MultiPoint{ns}{srs}>{members}</gml:MultiPoint>")
526        }
527        Geometry::MultiLineString(ml) => {
528            let members: String = ml
529                .iter()
530                .map(|l| {
531                    format!(
532                        "<gml:curveMember><gml:LineString><gml:posList>{}</gml:posList></gml:LineString></gml:curveMember>",
533                        fmt_coords(l)
534                    )
535                })
536                .collect();
537            format!("<gml:MultiCurve{ns}{srs}>{members}</gml:MultiCurve>")
538        }
539        Geometry::MultiPolygon(mp) => {
540            let members: String = mp
541                .iter()
542                .map(|p| {
543                    let inner = write_gml(&Geometry::Polygon(p.clone()), None)
544                        .replace(ns, "");
545                    format!("<gml:surfaceMember>{inner}</gml:surfaceMember>")
546                })
547                .collect();
548            format!("<gml:MultiSurface{ns}{srs}>{members}</gml:MultiSurface>")
549        }
550        other => format!("<!-- unsupported geometry: {other:?} -->"),
551    }
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    #[test]
559    fn parse_point_with_srs() {
560        let xml = r#"<gml:Point xmlns:gml="http://www.opengis.net/gml/3.2" srsName="EPSG:4326">
561            <gml:pos>51.5074 -0.1278</gml:pos></gml:Point>"#;
562        let g = parse_gml(xml).unwrap();
563        assert_eq!(g.srs_name.as_deref(), Some("EPSG:4326"));
564        assert_eq!(
565            g.geometry,
566            Geometry::Point(Point::new(51.5074, -0.1278))
567        );
568    }
569
570    #[test]
571    fn parse_linestring_poslist() {
572        let xml = r#"<LineString><posList>0 0 1 1 2 0</posList></LineString>"#;
573        let g = parse_gml(xml).unwrap();
574        match g.geometry {
575            Geometry::LineString(l) => assert_eq!(l.coords().count(), 3),
576            _ => panic!("expected linestring"),
577        }
578    }
579
580    #[test]
581    fn parse_polygon_with_hole() {
582        let xml = r#"<gml:Polygon xmlns:gml="http://www.opengis.net/gml/3.2">
583          <gml:exterior><gml:LinearRing>
584            <gml:posList>0 0 10 0 10 10 0 10 0 0</gml:posList>
585          </gml:LinearRing></gml:exterior>
586          <gml:interior><gml:LinearRing>
587            <gml:posList>4 4 6 4 6 6 4 6 4 4</gml:posList>
588          </gml:LinearRing></gml:interior>
589        </gml:Polygon>"#;
590        let g = parse_gml(xml).unwrap();
591        match g.geometry {
592            Geometry::Polygon(p) => {
593                assert_eq!(p.exterior().coords().count(), 5);
594                assert_eq!(p.interiors().len(), 1);
595            }
596            _ => panic!("expected polygon"),
597        }
598    }
599
600    #[test]
601    fn parse_3d_drops_z() {
602        let xml = r#"<Point srsDimension="3"><pos>1 2 99</pos></Point>"#;
603        let g = parse_gml(xml).unwrap();
604        assert_eq!(g.srs_dimension, 3);
605        assert_eq!(g.geometry, Geometry::Point(Point::new(1.0, 2.0)));
606    }
607
608    #[test]
609    fn parse_multisurface() {
610        let xml = r#"<gml:MultiSurface xmlns:gml="http://www.opengis.net/gml/3.2">
611          <gml:surfaceMember><gml:Polygon><gml:exterior><gml:LinearRing>
612            <gml:posList>0 0 1 0 1 1 0 0</gml:posList>
613          </gml:LinearRing></gml:exterior></gml:Polygon></gml:surfaceMember>
614          <gml:surfaceMember><gml:Polygon><gml:exterior><gml:LinearRing>
615            <gml:posList>5 5 6 5 6 6 5 5</gml:posList>
616          </gml:LinearRing></gml:exterior></gml:Polygon></gml:surfaceMember>
617        </gml:MultiSurface>"#;
618        let g = parse_gml(xml).unwrap();
619        match g.geometry {
620            Geometry::MultiPolygon(mp) => assert_eq!(mp.0.len(), 2),
621            _ => panic!("expected multipolygon"),
622        }
623    }
624
625    #[test]
626    fn roundtrip_polygon() {
627        let xml = r#"<Polygon><exterior><LinearRing>
628            <posList>0 0 4 0 4 4 0 0</posList></LinearRing></exterior></Polygon>"#;
629        let parsed = parse_gml(xml).unwrap();
630        let written = write_gml(&parsed.geometry, None);
631        let reparsed = parse_gml(&written).unwrap();
632        assert_eq!(parsed.geometry, reparsed.geometry);
633    }
634
635    #[test]
636    fn errors_are_reported() {
637        assert!(matches!(parse_gml("<foo/>"), Err(GmlError::NoGeometry)));
638        assert!(matches!(
639            parse_gml("<Point><pos>abc def</pos></Point>"),
640            Err(GmlError::BadNumber(_))
641        ));
642        assert!(matches!(
643            parse_gml("<Point><pos>1 2 3</pos></Point>"), // dim 2, 3 ordinates
644            Err(GmlError::BadCoordinates(_))
645        ));
646        assert!(matches!(
647            parse_gml("<Polygon></Polygon>"),
648            Err(GmlError::Structure(_))
649        ));
650    }
651}