LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gml - ogrgmldatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1520 1685 90.2 %
Date: 2025-09-10 17:48:50 Functions: 32 39 82.1 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  OGR
       4             :  * Purpose:  Implements OGRGMLDataSource class.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com>
       9             :  * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  *
      13             :  ******************************************************************************
      14             :  * Contributor: Alessandro Furieri, a.furieri@lqt.it
      15             :  * Portions of this module implementing GML_SKIP_RESOLVE_ELEMS HUGE
      16             :  * Developed for Faunalia ( http://www.faunalia.it) with funding from
      17             :  * Regione Toscana - Settore SISTEMA INFORMATIVO TERRITORIALE ED AMBIENTALE
      18             :  *
      19             :  ****************************************************************************/
      20             : 
      21             : #include "cpl_port.h"
      22             : #include "ogr_gml.h"
      23             : 
      24             : #include <algorithm>
      25             : #include <vector>
      26             : 
      27             : #include "cpl_conv.h"
      28             : #include "cpl_http.h"
      29             : #include "cpl_string.h"
      30             : #include "cpl_vsi_error.h"
      31             : #include "gmlreaderp.h"
      32             : #include "gmlregistry.h"
      33             : #include "gmlutils.h"
      34             : #include "ogr_p.h"
      35             : #include "ogr_schema_override.h"
      36             : #include "parsexsd.h"
      37             : #include "memdataset.h"
      38             : 
      39             : /************************************************************************/
      40             : /*                   ReplaceSpaceByPct20IfNeeded()                      */
      41             : /************************************************************************/
      42             : 
      43         142 : static CPLString ReplaceSpaceByPct20IfNeeded(const char *pszURL)
      44             : {
      45             :     // Replace ' ' by '%20'.
      46         142 :     CPLString osRet = pszURL;
      47         142 :     const char *pszNeedle = strstr(pszURL, "; ");
      48         142 :     if (pszNeedle)
      49             :     {
      50           2 :         char *pszTmp = static_cast<char *>(CPLMalloc(strlen(pszURL) + 2 + 1));
      51           2 :         const int nBeforeNeedle = static_cast<int>(pszNeedle - pszURL);
      52           2 :         memcpy(pszTmp, pszURL, nBeforeNeedle);
      53           2 :         strcpy(pszTmp + nBeforeNeedle, ";%20");
      54           2 :         strcpy(pszTmp + nBeforeNeedle + strlen(";%20"),
      55             :                pszNeedle + strlen("; "));
      56           2 :         osRet = pszTmp;
      57           2 :         CPLFree(pszTmp);
      58             :     }
      59             : 
      60         142 :     return osRet;
      61             : }
      62             : 
      63             : /************************************************************************/
      64             : /*                         OGRGMLDataSource()                         */
      65             : /************************************************************************/
      66             : 
      67         551 : OGRGMLDataSource::OGRGMLDataSource()
      68             :     : papoLayers(nullptr), nLayers(0), papszCreateOptions(nullptr),
      69             :       fpOutput(nullptr), bFpOutputIsNonSeekable(false),
      70             :       bFpOutputSingleFile(false), bBBOX3D(false), nBoundedByLocation(-1),
      71             :       nSchemaInsertLocation(-1), bIsOutputGML3(false),
      72             :       bIsOutputGML3Deegree(false), bIsOutputGML32(false),
      73             :       eSRSNameFormat(SRSNAME_SHORT), bWriteSpaceIndentation(true),
      74             :       poReader(nullptr), bOutIsTempFile(false), bExposeGMLId(false),
      75             :       bExposeFid(false), bIsWFS(false), bUseGlobalSRSName(false),
      76             :       m_bInvertAxisOrderIfLatLong(false), m_bConsiderEPSGAsURN(false),
      77             :       m_eSwapCoordinates(GML_SWAP_AUTO), m_bGetSecondaryGeometryOption(false),
      78             :       eReadMode(STANDARD), poStoredGMLFeature(nullptr),
      79         551 :       poLastReadLayer(nullptr), bEmptyAsNull(true)
      80             : {
      81         551 : }
      82             : 
      83             : /************************************************************************/
      84             : /*                          ~OGRGMLDataSource()                         */
      85             : /************************************************************************/
      86             : 
      87        1102 : OGRGMLDataSource::~OGRGMLDataSource()
      88             : {
      89         551 :     OGRGMLDataSource::Close();
      90        1102 : }
      91             : 
      92             : /************************************************************************/
      93             : /*                                 Close()                              */
      94             : /************************************************************************/
      95             : 
      96        1088 : CPLErr OGRGMLDataSource::Close()
      97             : {
      98        1088 :     CPLErr eErr = CE_None;
      99        1088 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     100             :     {
     101        1088 :         if (fpOutput && !m_bWriteError)
     102             :         {
     103          99 :             if (nLayers == 0)
     104           3 :                 WriteTopElements();
     105             : 
     106          99 :             const char *pszPrefix = GetAppPrefix();
     107          99 :             if (GMLFeatureCollection())
     108           1 :                 PrintLine(fpOutput, "</gml:FeatureCollection>");
     109          98 :             else if (RemoveAppPrefix())
     110           2 :                 PrintLine(fpOutput, "</FeatureCollection>");
     111             :             else
     112          96 :                 PrintLine(fpOutput, "</%s:FeatureCollection>", pszPrefix);
     113             : 
     114          99 :             if (bFpOutputIsNonSeekable)
     115             :             {
     116           0 :                 VSIFCloseL(fpOutput);
     117           0 :                 fpOutput = nullptr;
     118             :             }
     119             : 
     120          99 :             InsertHeader();
     121             : 
     122         198 :             if (!bFpOutputIsNonSeekable && nBoundedByLocation != -1 &&
     123          99 :                 VSIFSeekL(fpOutput, nBoundedByLocation, SEEK_SET) == 0)
     124             :             {
     125         166 :                 if (m_bWriteGlobalSRS && sBoundingRect.IsInit() &&
     126          67 :                     IsGML3Output())
     127             :                 {
     128          57 :                     bool bCoordSwap = false;
     129             :                     char *pszSRSName =
     130             :                         m_poWriteGlobalSRS
     131          57 :                             ? GML_GetSRSName(m_poWriteGlobalSRS.get(),
     132             :                                              eSRSNameFormat, &bCoordSwap)
     133          95 :                             : CPLStrdup("");
     134          57 :                     char szLowerCorner[75] = {};
     135          57 :                     char szUpperCorner[75] = {};
     136             : 
     137          57 :                     OGRWktOptions coordOpts;
     138             : 
     139          57 :                     if (OGRGMLDataSource::GetLayerCount() == 1)
     140             :                     {
     141          41 :                         OGRLayer *poLayer = OGRGMLDataSource::GetLayer(0);
     142          41 :                         if (poLayer->GetLayerDefn()->GetGeomFieldCount() == 1)
     143             :                         {
     144             :                             const auto &oCoordPrec =
     145          37 :                                 poLayer->GetLayerDefn()
     146          37 :                                     ->GetGeomFieldDefn(0)
     147          37 :                                     ->GetCoordinatePrecision();
     148          37 :                             if (oCoordPrec.dfXYResolution !=
     149             :                                 OGRGeomCoordinatePrecision::UNKNOWN)
     150             :                             {
     151           1 :                                 coordOpts.format = OGRWktFormat::F;
     152           1 :                                 coordOpts.xyPrecision =
     153             :                                     OGRGeomCoordinatePrecision::
     154           1 :                                         ResolutionToPrecision(
     155           1 :                                             oCoordPrec.dfXYResolution);
     156             :                             }
     157          37 :                             if (oCoordPrec.dfZResolution !=
     158             :                                 OGRGeomCoordinatePrecision::UNKNOWN)
     159             :                             {
     160           1 :                                 coordOpts.format = OGRWktFormat::F;
     161           1 :                                 coordOpts.zPrecision =
     162             :                                     OGRGeomCoordinatePrecision::
     163           1 :                                         ResolutionToPrecision(
     164           1 :                                             oCoordPrec.dfZResolution);
     165             :                             }
     166             :                         }
     167             :                     }
     168             : 
     169         114 :                     std::string wkt;
     170          57 :                     if (bCoordSwap)
     171             :                     {
     172          22 :                         wkt = OGRMakeWktCoordinate(
     173             :                             sBoundingRect.MinY, sBoundingRect.MinX,
     174          22 :                             sBoundingRect.MinZ, bBBOX3D ? 3 : 2, coordOpts);
     175          11 :                         memcpy(szLowerCorner, wkt.data(), wkt.size() + 1);
     176             : 
     177          22 :                         wkt = OGRMakeWktCoordinate(
     178             :                             sBoundingRect.MaxY, sBoundingRect.MaxX,
     179          22 :                             sBoundingRect.MaxZ, bBBOX3D ? 3 : 2, coordOpts);
     180          11 :                         memcpy(szUpperCorner, wkt.data(), wkt.size() + 1);
     181             :                     }
     182             :                     else
     183             :                     {
     184          92 :                         wkt = OGRMakeWktCoordinate(
     185             :                             sBoundingRect.MinX, sBoundingRect.MinY,
     186          92 :                             sBoundingRect.MinZ, bBBOX3D ? 3 : 2, coordOpts);
     187          46 :                         memcpy(szLowerCorner, wkt.data(), wkt.size() + 1);
     188             : 
     189          92 :                         wkt = OGRMakeWktCoordinate(
     190             :                             sBoundingRect.MaxX, sBoundingRect.MaxY,
     191          92 :                             sBoundingRect.MaxZ, (bBBOX3D) ? 3 : 2, coordOpts);
     192          46 :                         memcpy(szUpperCorner, wkt.data(), wkt.size() + 1);
     193             :                     }
     194          57 :                     if (bWriteSpaceIndentation)
     195          57 :                         VSIFPrintfL(fpOutput, "  ");
     196          57 :                     PrintLine(
     197             :                         fpOutput,
     198             :                         "<gml:boundedBy><gml:Envelope%s%s><gml:lowerCorner>%s"
     199             :                         "</gml:lowerCorner><gml:upperCorner>%s</"
     200             :                         "gml:upperCorner>"
     201             :                         "</gml:Envelope></gml:boundedBy>",
     202          57 :                         bBBOX3D ? " srsDimension=\"3\"" : "", pszSRSName,
     203             :                         szLowerCorner, szUpperCorner);
     204          57 :                     CPLFree(pszSRSName);
     205             :                 }
     206          42 :                 else if (m_bWriteGlobalSRS && sBoundingRect.IsInit())
     207             :                 {
     208          10 :                     if (bWriteSpaceIndentation)
     209          10 :                         VSIFPrintfL(fpOutput, "  ");
     210          10 :                     PrintLine(fpOutput, "<gml:boundedBy>");
     211          10 :                     if (bWriteSpaceIndentation)
     212          10 :                         VSIFPrintfL(fpOutput, "    ");
     213          10 :                     PrintLine(fpOutput, "<gml:Box>");
     214          10 :                     if (bWriteSpaceIndentation)
     215          10 :                         VSIFPrintfL(fpOutput, "      ");
     216          10 :                     VSIFPrintfL(fpOutput,
     217             :                                 "<gml:coord><gml:X>%.16g</gml:X>"
     218             :                                 "<gml:Y>%.16g</gml:Y>",
     219             :                                 sBoundingRect.MinX, sBoundingRect.MinY);
     220          10 :                     if (bBBOX3D)
     221           1 :                         VSIFPrintfL(fpOutput, "<gml:Z>%.16g</gml:Z>",
     222             :                                     sBoundingRect.MinZ);
     223          10 :                     PrintLine(fpOutput, "</gml:coord>");
     224          10 :                     if (bWriteSpaceIndentation)
     225          10 :                         VSIFPrintfL(fpOutput, "      ");
     226          10 :                     VSIFPrintfL(fpOutput,
     227             :                                 "<gml:coord><gml:X>%.16g</gml:X>"
     228             :                                 "<gml:Y>%.16g</gml:Y>",
     229             :                                 sBoundingRect.MaxX, sBoundingRect.MaxY);
     230          10 :                     if (bBBOX3D)
     231           1 :                         VSIFPrintfL(fpOutput, "<gml:Z>%.16g</gml:Z>",
     232             :                                     sBoundingRect.MaxZ);
     233          10 :                     PrintLine(fpOutput, "</gml:coord>");
     234          10 :                     if (bWriteSpaceIndentation)
     235          10 :                         VSIFPrintfL(fpOutput, "    ");
     236          10 :                     PrintLine(fpOutput, "</gml:Box>");
     237          10 :                     if (bWriteSpaceIndentation)
     238          10 :                         VSIFPrintfL(fpOutput, "  ");
     239          10 :                     PrintLine(fpOutput, "</gml:boundedBy>");
     240             :                 }
     241             :                 else
     242             :                 {
     243          32 :                     if (bWriteSpaceIndentation)
     244          32 :                         VSIFPrintfL(fpOutput, "  ");
     245          32 :                     if (IsGML3Output())
     246          32 :                         PrintLine(
     247             :                             fpOutput,
     248             :                             "<gml:boundedBy><gml:Null /></gml:boundedBy>");
     249             :                     else
     250           0 :                         PrintLine(fpOutput, "<gml:boundedBy><gml:null>missing"
     251             :                                             "</gml:null></gml:boundedBy>");
     252             :                 }
     253             :             }
     254             :         }
     255             : 
     256        1088 :         if (fpOutput)
     257         100 :             VSIFCloseL(fpOutput);
     258        1088 :         fpOutput = nullptr;
     259             : 
     260        1088 :         CSLDestroy(papszCreateOptions);
     261        1088 :         papszCreateOptions = nullptr;
     262             : 
     263        1794 :         for (int i = 0; i < nLayers; i++)
     264         706 :             delete papoLayers[i];
     265        1088 :         CPLFree(papoLayers);
     266        1088 :         papoLayers = nullptr;
     267        1088 :         nLayers = 0;
     268             : 
     269        1088 :         if (poReader)
     270             :         {
     271         447 :             if (bOutIsTempFile)
     272           0 :                 VSIUnlink(poReader->GetSourceFileName());
     273         447 :             delete poReader;
     274         447 :             poReader = nullptr;
     275             :         }
     276             : 
     277        1088 :         delete poStoredGMLFeature;
     278        1088 :         poStoredGMLFeature = nullptr;
     279             : 
     280        1088 :         if (m_bUnlinkXSDFilename)
     281             :         {
     282           7 :             VSIUnlink(osXSDFilename);
     283           7 :             m_bUnlinkXSDFilename = false;
     284             :         }
     285             : 
     286        1088 :         if (m_bWriteError)
     287           4 :             eErr = CE_Failure;
     288             :     }
     289        1088 :     return eErr;
     290             : }
     291             : 
     292             : /************************************************************************/
     293             : /*                            CheckHeader()                             */
     294             : /************************************************************************/
     295             : 
     296        1643 : bool OGRGMLDataSource::CheckHeader(const char *pszStr)
     297             : {
     298        1643 :     if (strstr(pszStr, "<wfs:FeatureCollection ") != nullptr)
     299         378 :         return true;
     300             : 
     301        1265 :     if (strstr(pszStr, "opengis.net/gml") == nullptr &&
     302         419 :         strstr(pszStr, "<csw:GetRecordsResponse") == nullptr)
     303             :     {
     304         362 :         return false;
     305             :     }
     306             : 
     307             :     // Ignore kml files
     308         903 :     if (strstr(pszStr, "<kml") != nullptr)
     309             :     {
     310           0 :         return false;
     311             :     }
     312             : 
     313             :     // Ignore .xsd schemas.
     314         903 :     if (strstr(pszStr, "<schema") != nullptr ||
     315         902 :         strstr(pszStr, "<xs:schema") != nullptr ||
     316         902 :         strstr(pszStr, "<xsd:schema") != nullptr)
     317             :     {
     318           3 :         return false;
     319             :     }
     320             : 
     321             :     // Ignore GeoRSS documents. They will be recognized by the GeoRSS driver.
     322         900 :     if (strstr(pszStr, "<rss") != nullptr &&
     323           4 :         strstr(pszStr, "xmlns:georss") != nullptr)
     324             :     {
     325           4 :         return false;
     326             :     }
     327             : 
     328             :     // Ignore OpenJUMP .jml documents.
     329             :     // They will be recognized by the OpenJUMP driver.
     330         896 :     if (strstr(pszStr, "<JCSDataFile") != nullptr)
     331             :     {
     332          42 :         return false;
     333             :     }
     334             : 
     335             :     // Ignore OGR WFS xml description files, or WFS Capabilities results.
     336         854 :     if (strstr(pszStr, "<OGRWFSDataSource>") != nullptr ||
     337         852 :         strstr(pszStr, "<wfs:WFS_Capabilities") != nullptr)
     338             :     {
     339           2 :         return false;
     340             :     }
     341             : 
     342             :     // Ignore WMTS capabilities results.
     343         852 :     if (strstr(pszStr, "http://www.opengis.net/wmts/1.0") != nullptr)
     344             :     {
     345           1 :         return false;
     346             :     }
     347             : 
     348         851 :     return true;
     349             : }
     350             : 
     351             : /************************************************************************/
     352             : /*                          ExtractSRSName()                            */
     353             : /************************************************************************/
     354             : 
     355          31 : static bool ExtractSRSName(const char *pszXML, char *szSRSName,
     356             :                            size_t sizeof_szSRSName)
     357             : {
     358          31 :     szSRSName[0] = '\0';
     359             : 
     360          31 :     const char *pszSRSName = strstr(pszXML, "srsName=\"");
     361          31 :     if (pszSRSName != nullptr)
     362             :     {
     363          27 :         pszSRSName += 9;
     364          27 :         const char *pszEndQuote = strchr(pszSRSName, '"');
     365          27 :         if (pszEndQuote != nullptr &&
     366          27 :             static_cast<size_t>(pszEndQuote - pszSRSName) < sizeof_szSRSName)
     367             :         {
     368          27 :             memcpy(szSRSName, pszSRSName, pszEndQuote - pszSRSName);
     369          27 :             szSRSName[pszEndQuote - pszSRSName] = '\0';
     370          27 :             return true;
     371             :         }
     372             :     }
     373           4 :     return false;
     374             : }
     375             : 
     376             : /************************************************************************/
     377             : /*                                Open()                                */
     378             : /************************************************************************/
     379             : 
     380         450 : bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo)
     381             : 
     382             : {
     383             :     // Extract XSD filename from connection string if present.
     384         450 :     osFilename = poOpenInfo->pszFilename;
     385         450 :     const char *pszXSDFilenameTmp = strstr(poOpenInfo->pszFilename, ",xsd=");
     386         450 :     if (pszXSDFilenameTmp != nullptr)
     387             :     {
     388           2 :         osFilename.resize(pszXSDFilenameTmp - poOpenInfo->pszFilename);
     389           2 :         osXSDFilename = pszXSDFilenameTmp + strlen(",xsd=");
     390             :     }
     391             :     else
     392             :     {
     393             :         osXSDFilename =
     394         448 :             CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "XSD", "");
     395             :     }
     396             : 
     397         450 :     const char *pszFilename = osFilename.c_str();
     398             : 
     399             :     // Open the source file.
     400         450 :     VSILFILE *fpToClose = nullptr;
     401         450 :     VSILFILE *fp = nullptr;
     402         450 :     if (poOpenInfo->fpL != nullptr)
     403             :     {
     404         448 :         fp = poOpenInfo->fpL;
     405         448 :         VSIFSeekL(fp, 0, SEEK_SET);
     406             :     }
     407             :     else
     408             :     {
     409           2 :         fp = VSIFOpenL(pszFilename, "r");
     410           2 :         if (fp == nullptr)
     411           0 :             return false;
     412           2 :         fpToClose = fp;
     413             :     }
     414             : 
     415             :     // Load a header chunk and check for signs it is GML.
     416         450 :     char szHeader[4096] = {};
     417         450 :     size_t nRead = VSIFReadL(szHeader, 1, sizeof(szHeader) - 1, fp);
     418         450 :     if (nRead == 0)
     419             :     {
     420           0 :         if (fpToClose)
     421           0 :             VSIFCloseL(fpToClose);
     422           0 :         return false;
     423             :     }
     424         450 :     szHeader[nRead] = '\0';
     425             : 
     426         900 :     CPLString osWithVsiGzip;
     427             : 
     428             :     // Might be a OS-Mastermap gzipped GML, so let be nice and try to open
     429             :     // it transparently with /vsigzip/.
     430         902 :     if (static_cast<GByte>(szHeader[0]) == 0x1f &&
     431           2 :         static_cast<GByte>(szHeader[1]) == 0x8b &&
     432         454 :         EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "gz") &&
     433           2 :         !STARTS_WITH(pszFilename, "/vsigzip/"))
     434             :     {
     435           2 :         if (fpToClose)
     436           0 :             VSIFCloseL(fpToClose);
     437           2 :         fpToClose = nullptr;
     438           2 :         osWithVsiGzip = "/vsigzip/";
     439           2 :         osWithVsiGzip += pszFilename;
     440             : 
     441           2 :         pszFilename = osWithVsiGzip;
     442             : 
     443           2 :         fp = fpToClose = VSIFOpenL(pszFilename, "r");
     444           2 :         if (fp == nullptr)
     445           0 :             return false;
     446             : 
     447           2 :         nRead = VSIFReadL(szHeader, 1, sizeof(szHeader) - 1, fp);
     448           2 :         if (nRead == 0)
     449             :         {
     450           0 :             VSIFCloseL(fpToClose);
     451           0 :             return false;
     452             :         }
     453           2 :         szHeader[nRead] = '\0';
     454             :     }
     455             : 
     456             :     // Check for a UTF-8 BOM and skip if found.
     457             : 
     458             :     // TODO: BOM is variable-length parameter and depends on encoding. */
     459             :     // Add BOM detection for other encodings.
     460             : 
     461             :     // Used to skip to actual beginning of XML data
     462         450 :     char *szPtr = szHeader;
     463             : 
     464         450 :     if ((static_cast<unsigned char>(szHeader[0]) == 0xEF) &&
     465           4 :         (static_cast<unsigned char>(szHeader[1]) == 0xBB) &&
     466           4 :         (static_cast<unsigned char>(szHeader[2]) == 0xBF))
     467             :     {
     468           4 :         szPtr += 3;
     469             :     }
     470             : 
     471         450 :     bool bExpatCompatibleEncoding = false;
     472             : 
     473         450 :     const char *pszEncoding = strstr(szPtr, "encoding=");
     474         450 :     if (pszEncoding)
     475         363 :         bExpatCompatibleEncoding =
     476         726 :             (pszEncoding[9] == '\'' || pszEncoding[9] == '"') &&
     477         363 :             (STARTS_WITH_CI(pszEncoding + 10, "UTF-8") ||
     478           2 :              STARTS_WITH_CI(pszEncoding + 10, "ISO-8859-15") ||
     479           2 :              (STARTS_WITH_CI(pszEncoding + 10, "ISO-8859-1") &&
     480           2 :               pszEncoding[20] == pszEncoding[9]));
     481             :     else
     482          87 :         bExpatCompatibleEncoding = true;  // utf-8 is the default.
     483             : 
     484         869 :     const bool bHas3D = strstr(szPtr, "srsDimension=\"3\"") != nullptr ||
     485         419 :                         strstr(szPtr, "<gml:Z>") != nullptr;
     486             : 
     487             :     // Here, we expect the opening chevrons of GML tree root element.
     488         450 :     if (szPtr[0] != '<' || !CheckHeader(szPtr))
     489             :     {
     490           3 :         if (fpToClose)
     491           0 :             VSIFCloseL(fpToClose);
     492           3 :         return false;
     493             :     }
     494             : 
     495             :     // Now we definitely own the file descriptor.
     496         447 :     if (fp == poOpenInfo->fpL)
     497         443 :         poOpenInfo->fpL = nullptr;
     498             : 
     499             :     // Small optimization: if we parse a <wfs:FeatureCollection> and
     500             :     // that numberOfFeatures is set, we can use it to set the FeatureCount
     501             :     // but *ONLY* if there's just one class.
     502         447 :     const char *pszFeatureCollection = strstr(szPtr, "wfs:FeatureCollection");
     503         447 :     if (pszFeatureCollection == nullptr)
     504             :         // GML 3.2.1 output.
     505         301 :         pszFeatureCollection = strstr(szPtr, "gml:FeatureCollection");
     506         447 :     if (pszFeatureCollection == nullptr)
     507             :     {
     508             :         // Deegree WFS 1.0.0 output.
     509         285 :         pszFeatureCollection = strstr(szPtr, "<FeatureCollection");
     510         285 :         if (pszFeatureCollection &&
     511           7 :             strstr(szPtr, "xmlns:wfs=\"http://www.opengis.net/wfs\"") ==
     512             :                 nullptr)
     513           6 :             pszFeatureCollection = nullptr;
     514             :     }
     515             : 
     516         447 :     GIntBig nNumberOfFeatures = 0;
     517         447 :     if (pszFeatureCollection)
     518             :     {
     519         163 :         bExposeGMLId = true;
     520         163 :         bIsWFS = true;
     521         163 :         const char *pszNumberOfFeatures = strstr(szPtr, "numberOfFeatures=");
     522         163 :         if (pszNumberOfFeatures)
     523             :         {
     524          46 :             pszNumberOfFeatures += 17;
     525          46 :             char ch = pszNumberOfFeatures[0];
     526          46 :             if ((ch == '\'' || ch == '"') &&
     527          46 :                 strchr(pszNumberOfFeatures + 1, ch) != nullptr)
     528             :             {
     529          46 :                 nNumberOfFeatures = CPLAtoGIntBig(pszNumberOfFeatures + 1);
     530             :             }
     531             :         }
     532         117 :         else if ((pszNumberOfFeatures = strstr(szPtr, "numberReturned=")) !=
     533             :                  nullptr)
     534             :         {
     535             :             // WFS 2.0.0
     536          94 :             pszNumberOfFeatures += 15;
     537          94 :             char ch = pszNumberOfFeatures[0];
     538          94 :             if ((ch == '\'' || ch == '"') &&
     539          94 :                 strchr(pszNumberOfFeatures + 1, ch) != nullptr)
     540             :             {
     541             :                 // 'unknown' might be a valid value in a corrected version of
     542             :                 // WFS 2.0 but it will also evaluate to 0, that is considered as
     543             :                 // unknown, so nothing particular to do.
     544          94 :                 nNumberOfFeatures = CPLAtoGIntBig(pszNumberOfFeatures + 1);
     545             :             }
     546             :         }
     547             :     }
     548         284 :     else if (STARTS_WITH(pszFilename, "/vsimem/") &&
     549         132 :              strstr(pszFilename, "_ogr_wfs_"))
     550             :     {
     551             :         // http://regis.intergraph.com/wfs/dcmetro/request.asp? returns a
     552             :         // <G:FeatureCollection> Who knows what servers can return?  When
     553             :         // in the context of the WFS driver always expose the gml:id to avoid
     554             :         // later crashes.
     555           0 :         bExposeGMLId = true;
     556           0 :         bIsWFS = true;
     557             :     }
     558             :     else
     559             :     {
     560         389 :         bExposeGMLId = strstr(szPtr, " gml:id=\"") != nullptr ||
     561         105 :                        strstr(szPtr, " gml:id='") != nullptr;
     562         496 :         bExposeFid = strstr(szPtr, " fid=\"") != nullptr ||
     563         212 :                      strstr(szPtr, " fid='") != nullptr;
     564             :     }
     565             : 
     566             :     const char *pszExposeGMLId =
     567         447 :         CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "EXPOSE_GML_ID",
     568             :                              CPLGetConfigOption("GML_EXPOSE_GML_ID", nullptr));
     569         447 :     if (pszExposeGMLId)
     570          64 :         bExposeGMLId = CPLTestBool(pszExposeGMLId);
     571             : 
     572             :     const char *pszExposeFid =
     573         447 :         CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "EXPOSE_FID",
     574             :                              CPLGetConfigOption("GML_EXPOSE_FID", nullptr));
     575             : 
     576         447 :     if (pszExposeFid)
     577           1 :         bExposeFid = CPLTestBool(pszExposeFid);
     578             : 
     579         447 :     const bool bHintConsiderEPSGAsURN =
     580         447 :         strstr(szPtr, "xmlns:fme=\"http://www.safe.com/gml/fme\"") != nullptr;
     581             : 
     582         447 :     char szSRSName[128] = {};
     583             : 
     584             :     // MTKGML.
     585         447 :     if (strstr(szPtr, "<Maastotiedot") != nullptr)
     586             :     {
     587           3 :         if (strstr(szPtr,
     588             :                    "http://xml.nls.fi/XML/Namespace/"
     589             :                    "Maastotietojarjestelma/SiirtotiedostonMalli/2011-02") ==
     590             :             nullptr)
     591           1 :             CPLDebug("GML", "Warning: a MTKGML file was detected, "
     592             :                             "but its namespace is unknown");
     593           3 :         bUseGlobalSRSName = true;
     594           3 :         if (!ExtractSRSName(szPtr, szSRSName, sizeof(szSRSName)))
     595           1 :             strcpy(szSRSName, "EPSG:3067");
     596             :     }
     597             : 
     598         447 :     const char *pszSchemaLocation = strstr(szPtr, "schemaLocation=");
     599         447 :     if (pszSchemaLocation)
     600         391 :         pszSchemaLocation += strlen("schemaLocation=");
     601             : 
     602         447 :     bool bCheckAuxFile = true;
     603         447 :     if (STARTS_WITH(pszFilename, "/vsicurl_streaming/"))
     604           2 :         bCheckAuxFile = false;
     605         445 :     else if (STARTS_WITH(pszFilename, "/vsicurl/") &&
     606           1 :              (strstr(pszFilename, "?SERVICE=") ||
     607           1 :               strstr(pszFilename, "&SERVICE=")))
     608           0 :         bCheckAuxFile = false;
     609             : 
     610         447 :     bool bIsWFSJointLayer = bIsWFS && strstr(szPtr, "<wfs:Tuple>");
     611         447 :     if (bIsWFSJointLayer)
     612          50 :         bExposeGMLId = false;
     613             : 
     614             :     // We assume now that it is GML.  Instantiate a GMLReader on it.
     615             :     const char *pszReadMode =
     616         447 :         CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "READ_MODE",
     617             :                              CPLGetConfigOption("GML_READ_MODE", "AUTO"));
     618         447 :     if (EQUAL(pszReadMode, "AUTO"))
     619         444 :         pszReadMode = nullptr;
     620         447 :     if (pszReadMode == nullptr || EQUAL(pszReadMode, "STANDARD"))
     621         444 :         eReadMode = STANDARD;
     622           3 :     else if (EQUAL(pszReadMode, "SEQUENTIAL_LAYERS"))
     623           2 :         eReadMode = SEQUENTIAL_LAYERS;
     624           1 :     else if (EQUAL(pszReadMode, "INTERLEAVED_LAYERS"))
     625           1 :         eReadMode = INTERLEAVED_LAYERS;
     626             :     else
     627             :     {
     628           0 :         CPLDebug("GML",
     629             :                  "Unrecognized value for GML_READ_MODE configuration option.");
     630             :     }
     631             : 
     632         894 :     m_bInvertAxisOrderIfLatLong = CPLTestBool(CSLFetchNameValueDef(
     633         447 :         poOpenInfo->papszOpenOptions, "INVERT_AXIS_ORDER_IF_LAT_LONG",
     634             :         CPLGetConfigOption("GML_INVERT_AXIS_ORDER_IF_LAT_LONG", "YES")));
     635             : 
     636         447 :     const char *pszConsiderEPSGAsURN = CSLFetchNameValueDef(
     637         447 :         poOpenInfo->papszOpenOptions, "CONSIDER_EPSG_AS_URN",
     638             :         CPLGetConfigOption("GML_CONSIDER_EPSG_AS_URN", "AUTO"));
     639         447 :     if (!EQUAL(pszConsiderEPSGAsURN, "AUTO"))
     640           0 :         m_bConsiderEPSGAsURN = CPLTestBool(pszConsiderEPSGAsURN);
     641         447 :     else if (bHintConsiderEPSGAsURN)
     642             :     {
     643             :         // GML produced by FME (at least CanVec GML) seem to honour EPSG axis
     644             :         // ordering.
     645           5 :         CPLDebug("GML", "FME-produced GML --> "
     646             :                         "consider that GML_CONSIDER_EPSG_AS_URN is set to YES");
     647           5 :         m_bConsiderEPSGAsURN = true;
     648             :     }
     649             :     else
     650             :     {
     651         442 :         m_bConsiderEPSGAsURN = false;
     652             :     }
     653             : 
     654         447 :     const char *pszSwapCoordinates = CSLFetchNameValueDef(
     655         447 :         poOpenInfo->papszOpenOptions, "SWAP_COORDINATES",
     656             :         CPLGetConfigOption("GML_SWAP_COORDINATES", "AUTO"));
     657         453 :     m_eSwapCoordinates = EQUAL(pszSwapCoordinates, "AUTO") ? GML_SWAP_AUTO
     658           6 :                          : CPLTestBool(pszSwapCoordinates) ? GML_SWAP_YES
     659             :                                                            : GML_SWAP_NO;
     660             : 
     661         447 :     m_bGetSecondaryGeometryOption =
     662         447 :         CPLTestBool(CPLGetConfigOption("GML_GET_SECONDARY_GEOM", "NO"));
     663             : 
     664             :     // EXPAT is faster than Xerces, so when it is safe to use it, use it!
     665             :     // The only interest of Xerces is for rare encodings that Expat doesn't
     666             :     // handle, but UTF-8 is well handled by Expat.
     667         447 :     bool bUseExpatParserPreferably = bExpatCompatibleEncoding;
     668             : 
     669             :     // Override default choice.
     670         447 :     const char *pszGMLParser = CPLGetConfigOption("GML_PARSER", nullptr);
     671         447 :     if (pszGMLParser)
     672             :     {
     673           4 :         if (EQUAL(pszGMLParser, "EXPAT"))
     674           2 :             bUseExpatParserPreferably = true;
     675           2 :         else if (EQUAL(pszGMLParser, "XERCES"))
     676           2 :             bUseExpatParserPreferably = false;
     677             :     }
     678             : 
     679         447 :     poReader =
     680         894 :         CreateGMLReader(bUseExpatParserPreferably, m_bInvertAxisOrderIfLatLong,
     681         447 :                         m_bConsiderEPSGAsURN, m_eSwapCoordinates,
     682         447 :                         m_bGetSecondaryGeometryOption);
     683         447 :     if (poReader == nullptr)
     684             :     {
     685           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     686             :                  "File %s appears to be GML but the GML reader can't\n"
     687             :                  "be instantiated, likely because Xerces or Expat support was\n"
     688             :                  "not configured in.",
     689             :                  pszFilename);
     690           0 :         VSIFCloseL(fp);
     691           0 :         return false;
     692             :     }
     693             : 
     694         447 :     poReader->SetSourceFile(pszFilename);
     695         447 :     auto poGMLReader = cpl::down_cast<GMLReader *>(poReader);
     696         447 :     poGMLReader->SetIsWFSJointLayer(bIsWFSJointLayer);
     697         447 :     bEmptyAsNull =
     698         447 :         CPLFetchBool(poOpenInfo->papszOpenOptions, "EMPTY_AS_NULL", true);
     699         447 :     poGMLReader->SetEmptyAsNull(bEmptyAsNull);
     700         447 :     poGMLReader->SetReportAllAttributes(CPLFetchBool(
     701         447 :         poOpenInfo->papszOpenOptions, "GML_ATTRIBUTES_TO_OGR_FIELDS",
     702         447 :         CPLTestBool(CPLGetConfigOption("GML_ATTRIBUTES_TO_OGR_FIELDS", "NO"))));
     703         447 :     poGMLReader->SetUseBBOX(
     704         447 :         CPLFetchBool(poOpenInfo->papszOpenOptions, "USE_BBOX", false));
     705             : 
     706             :     // Find <gml:description>, <gml:name> and <gml:boundedBy> and if it is
     707             :     // a standalone geometry
     708             :     // Also look for <gml:description>, <gml:identifier> and <gml:name> inside
     709             :     // a feature
     710         447 :     FindAndParseTopElements(fp);
     711             : 
     712         447 :     if (m_poStandaloneGeom)
     713             :     {
     714           1 :         papoLayers = static_cast<OGRLayer **>(CPLMalloc(sizeof(OGRLayer *)));
     715           1 :         nLayers = 1;
     716             :         auto poLayer = new OGRMemLayer(
     717             :             "geometry",
     718           1 :             m_oStandaloneGeomSRS.IsEmpty() ? nullptr : &m_oStandaloneGeomSRS,
     719           1 :             m_poStandaloneGeom->getGeometryType());
     720           1 :         papoLayers[0] = poLayer;
     721           1 :         OGRFeature *poFeature = new OGRFeature(poLayer->GetLayerDefn());
     722           1 :         poFeature->SetGeometryDirectly(m_poStandaloneGeom.release());
     723           1 :         CPL_IGNORE_RET_VAL(poLayer->CreateFeature(poFeature));
     724           1 :         delete poFeature;
     725           1 :         poLayer->SetUpdatable(false);
     726           1 :         VSIFCloseL(fp);
     727           1 :         return true;
     728             :     }
     729             : 
     730         446 :     if (szSRSName[0] != '\0')
     731           3 :         poReader->SetGlobalSRSName(szSRSName);
     732             : 
     733             :     const bool bIsWFSFromServer =
     734         446 :         CPLString(pszFilename).ifind("SERVICE=WFS") != std::string::npos;
     735             : 
     736             :     // Resolve the xlinks in the source file and save it with the
     737             :     // extension ".resolved.gml". The source file will to set to that.
     738         446 :     char *pszXlinkResolvedFilename = nullptr;
     739         446 :     const char *pszOption = CPLGetConfigOption("GML_SAVE_RESOLVED_TO", nullptr);
     740         446 :     bool bResolve = true;
     741         446 :     bool bHugeFile = false;
     742         446 :     if (bIsWFSFromServer ||
     743           0 :         (pszOption != nullptr && STARTS_WITH_CI(pszOption, "SAME")))
     744             :     {
     745             :         // "SAME" will overwrite the existing gml file.
     746          59 :         pszXlinkResolvedFilename = CPLStrdup(pszFilename);
     747             :     }
     748         387 :     else if (pszOption != nullptr && CPLStrnlen(pszOption, 5) >= 5 &&
     749           0 :              STARTS_WITH_CI(pszOption - 4 + strlen(pszOption), ".gml"))
     750             :     {
     751             :         // Any string ending with ".gml" will try and write to it.
     752           0 :         pszXlinkResolvedFilename = CPLStrdup(pszOption);
     753             :     }
     754             :     else
     755             :     {
     756             :         // When no option is given or is not recognised,
     757             :         // use the same file name with the extension changed to .resolved.gml
     758         387 :         pszXlinkResolvedFilename = CPLStrdup(
     759         774 :             CPLResetExtensionSafe(pszFilename, "resolved.gml").c_str());
     760             : 
     761             :         // Check if the file already exists.
     762             :         VSIStatBufL sResStatBuf, sGMLStatBuf;
     763         774 :         if (bCheckAuxFile &&
     764         387 :             VSIStatL(pszXlinkResolvedFilename, &sResStatBuf) == 0)
     765             :         {
     766          10 :             if (VSIStatL(pszFilename, &sGMLStatBuf) == 0 &&
     767           5 :                 sGMLStatBuf.st_mtime > sResStatBuf.st_mtime)
     768             :             {
     769           0 :                 CPLDebug("GML",
     770             :                          "Found %s but ignoring because it appears\n"
     771             :                          "be older than the associated GML file.",
     772             :                          pszXlinkResolvedFilename);
     773             :             }
     774             :             else
     775             :             {
     776           5 :                 poReader->SetSourceFile(pszXlinkResolvedFilename);
     777           5 :                 bResolve = false;
     778             :             }
     779             :         }
     780             :     }
     781             : 
     782         446 :     const char *pszSkipOption = CSLFetchNameValueDef(
     783         446 :         poOpenInfo->papszOpenOptions, "SKIP_RESOLVE_ELEMS",
     784             :         CPLGetConfigOption("GML_SKIP_RESOLVE_ELEMS", "ALL"));
     785             : 
     786         446 :     char **papszSkip = nullptr;
     787         446 :     if (EQUAL(pszSkipOption, "ALL"))
     788         433 :         bResolve = false;
     789          13 :     else if (EQUAL(pszSkipOption, "HUGE"))
     790             :         // Exactly as NONE, but intended for HUGE files
     791           5 :         bHugeFile = true;
     792           8 :     else if (!EQUAL(pszSkipOption, "NONE"))  // Use this to resolve everything.
     793           0 :         papszSkip = CSLTokenizeString2(
     794             :             pszSkipOption, ",", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES);
     795         446 :     bool bHaveSchema = false;
     796         446 :     bool bSchemaDone = false;
     797             : 
     798             :     // Is some GML Feature Schema (.gfs) TEMPLATE required?
     799             :     const char *pszGFSTemplateName =
     800         446 :         CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "GFS_TEMPLATE",
     801             :                              CPLGetConfigOption("GML_GFS_TEMPLATE", nullptr));
     802         446 :     if (pszGFSTemplateName != nullptr)
     803             :     {
     804             :         // Attempt to load the GFS TEMPLATE.
     805           2 :         bHaveSchema = poReader->LoadClasses(pszGFSTemplateName);
     806             :     }
     807             : 
     808         446 :     if (bResolve)
     809             :     {
     810          13 :         if (bHugeFile)
     811             :         {
     812           5 :             bSchemaDone = true;
     813             :             bool bSqliteIsTempFile =
     814           5 :                 CPLTestBool(CPLGetConfigOption("GML_HUGE_TEMPFILE", "YES"));
     815             :             int iSqliteCacheMB =
     816           5 :                 atoi(CPLGetConfigOption("OGR_SQLITE_CACHE", "0"));
     817          10 :             if (poReader->HugeFileResolver(pszXlinkResolvedFilename,
     818             :                                            bSqliteIsTempFile,
     819           5 :                                            iSqliteCacheMB) == false)
     820             :             {
     821             :                 // Assume an error has been reported.
     822           0 :                 VSIFCloseL(fp);
     823           0 :                 CPLFree(pszXlinkResolvedFilename);
     824           0 :                 return false;
     825             :             }
     826             :         }
     827             :         else
     828             :         {
     829           8 :             poReader->ResolveXlinks(pszXlinkResolvedFilename, &bOutIsTempFile,
     830           8 :                                     papszSkip);
     831             :         }
     832             :     }
     833             : 
     834         446 :     CPLFree(pszXlinkResolvedFilename);
     835         446 :     pszXlinkResolvedFilename = nullptr;
     836         446 :     CSLDestroy(papszSkip);
     837         446 :     papszSkip = nullptr;
     838             : 
     839             :     // If the source filename for the reader is still the GML filename, then
     840             :     // we can directly provide the file pointer. Otherwise close it.
     841         446 :     if (strcmp(poReader->GetSourceFileName(), pszFilename) == 0)
     842         428 :         poReader->SetFP(fp);
     843             :     else
     844          18 :         VSIFCloseL(fp);
     845         446 :     fp = nullptr;
     846             : 
     847             :     // Is a prescan required?
     848         446 :     if (bHaveSchema && !bSchemaDone)
     849             :     {
     850             :         // We must detect which layers are actually present in the .gml
     851             :         // and how many features they have.
     852           2 :         if (!poReader->PrescanForTemplate())
     853             :         {
     854             :             // Assume an error has been reported.
     855           0 :             return false;
     856             :         }
     857             :     }
     858             : 
     859         892 :     CPLString osGFSFilename;
     860         446 :     if (!bIsWFSFromServer)
     861             :     {
     862         387 :         osGFSFilename = CPLResetExtensionSafe(pszFilename, "gfs");
     863         387 :         if (STARTS_WITH(osGFSFilename, "/vsigzip/"))
     864           2 :             osGFSFilename = osGFSFilename.substr(strlen("/vsigzip/"));
     865             :     }
     866             : 
     867             :     // Can we find a GML Feature Schema (.gfs) for the input file?
     868         826 :     if (!osGFSFilename.empty() && !bHaveSchema && !bSchemaDone &&
     869         380 :         osXSDFilename.empty())
     870             :     {
     871             :         VSIStatBufL sGFSStatBuf;
     872         377 :         if (bCheckAuxFile && VSIStatL(osGFSFilename, &sGFSStatBuf) == 0)
     873             :         {
     874             :             VSIStatBufL sGMLStatBuf;
     875         102 :             if (VSIStatL(pszFilename, &sGMLStatBuf) == 0 &&
     876          51 :                 sGMLStatBuf.st_mtime > sGFSStatBuf.st_mtime)
     877             :             {
     878           1 :                 CPLDebug("GML",
     879             :                          "Found %s but ignoring because it appears\n"
     880             :                          "be older than the associated GML file.",
     881             :                          osGFSFilename.c_str());
     882             :             }
     883             :             else
     884             :             {
     885          50 :                 bHaveSchema = poReader->LoadClasses(osGFSFilename);
     886          50 :                 if (bHaveSchema)
     887             :                 {
     888             :                     const std::string osXSDFilenameTmp =
     889          96 :                         CPLResetExtensionSafe(pszFilename, "xsd");
     890          48 :                     if (VSIStatExL(osXSDFilenameTmp.c_str(), &sGMLStatBuf,
     891          48 :                                    VSI_STAT_EXISTS_FLAG) == 0)
     892             :                     {
     893           0 :                         CPLDebug("GML", "Using %s file, ignoring %s",
     894             :                                  osGFSFilename.c_str(),
     895             :                                  osXSDFilenameTmp.c_str());
     896             :                     }
     897             :                 }
     898             :             }
     899             :         }
     900             :     }
     901             : 
     902             :     // Can we find an xsd which might conform to the GML3 Level 0
     903             :     // profile?  We really ought to look for it based on the rules
     904             :     // schemaLocation in the GML feature collection but for now we
     905             :     // just hopes it is in the same director with the same name.
     906             : 
     907         446 :     bool bHasFoundXSD = false;
     908             : 
     909         446 :     if (!bHaveSchema)
     910             :     {
     911         396 :         char **papszTypeNames = nullptr;
     912             : 
     913             :         VSIStatBufL sXSDStatBuf;
     914         396 :         if (osXSDFilename.empty())
     915             :         {
     916         334 :             osXSDFilename = CPLResetExtensionSafe(pszFilename, "xsd");
     917         334 :             if (bCheckAuxFile && VSIStatExL(osXSDFilename, &sXSDStatBuf,
     918             :                                             VSI_STAT_EXISTS_FLAG) == 0)
     919             :             {
     920         213 :                 bHasFoundXSD = true;
     921             :             }
     922             :         }
     923             :         else
     924             :         {
     925          62 :             if (STARTS_WITH(osXSDFilename, "http://") ||
     926         124 :                 STARTS_WITH(osXSDFilename, "https://") ||
     927          62 :                 VSIStatExL(osXSDFilename, &sXSDStatBuf, VSI_STAT_EXISTS_FLAG) ==
     928             :                     0)
     929             :             {
     930          62 :                 bHasFoundXSD = true;
     931             :             }
     932             :         }
     933             : 
     934             :         // If not found, try if there is a schema in the gml_registry.xml
     935             :         // that might match a declared namespace and featuretype.
     936         396 :         if (!bHasFoundXSD)
     937             :         {
     938             :             GMLRegistry oRegistry(
     939         121 :                 CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "REGISTRY",
     940         242 :                                      CPLGetConfigOption("GML_REGISTRY", "")));
     941         121 :             if (oRegistry.Parse())
     942             :             {
     943         242 :                 CPLString osHeader(szHeader);
     944         811 :                 for (size_t iNS = 0; iNS < oRegistry.aoNamespaces.size(); iNS++)
     945             :                 {
     946             :                     GMLRegistryNamespace &oNamespace =
     947         701 :                         oRegistry.aoNamespaces[iNS];
     948             :                     // When namespace is omitted or fit with case sensitive
     949             :                     // match for name space prefix, then go next to find feature
     950             :                     // match.
     951             :                     //
     952             :                     // Case sensitive comparison since below test that also
     953             :                     // uses the namespace prefix is case sensitive.
     954        1288 :                     if (!oNamespace.osPrefix.empty() &&
     955         587 :                         osHeader.find(CPLSPrintf(
     956             :                             "xmlns:%s", oNamespace.osPrefix.c_str())) ==
     957             :                             std::string::npos)
     958             :                     {
     959             :                         // namespace does not match with one of registry
     960             :                         // definition. go to next entry.
     961         580 :                         continue;
     962             :                     }
     963             : 
     964             :                     const char *pszURIToFind =
     965         121 :                         CPLSPrintf("\"%s\"", oNamespace.osURI.c_str());
     966         121 :                     if (strstr(szHeader, pszURIToFind) != nullptr)
     967             :                     {
     968          11 :                         if (oNamespace.bUseGlobalSRSName)
     969           7 :                             bUseGlobalSRSName = true;
     970             : 
     971          40 :                         for (size_t iTypename = 0;
     972          40 :                              iTypename < oNamespace.aoFeatureTypes.size();
     973             :                              iTypename++)
     974             :                         {
     975          40 :                             const char *pszElementToFind = nullptr;
     976             : 
     977             :                             GMLRegistryFeatureType &oFeatureType =
     978          40 :                                 oNamespace.aoFeatureTypes[iTypename];
     979             : 
     980          40 :                             if (!oNamespace.osPrefix.empty())
     981             :                             {
     982          15 :                                 if (!oFeatureType.osElementValue.empty())
     983           4 :                                     pszElementToFind = CPLSPrintf(
     984             :                                         "%s:%s>%s", oNamespace.osPrefix.c_str(),
     985             :                                         oFeatureType.osElementName.c_str(),
     986             :                                         oFeatureType.osElementValue.c_str());
     987             :                                 else
     988          11 :                                     pszElementToFind = CPLSPrintf(
     989             :                                         "%s:%s", oNamespace.osPrefix.c_str(),
     990             :                                         oFeatureType.osElementName.c_str());
     991             :                             }
     992             :                             else
     993             :                             {
     994          25 :                                 if (!oFeatureType.osElementValue.empty())
     995           0 :                                     pszElementToFind = CPLSPrintf(
     996             :                                         "%s>%s",
     997             :                                         oFeatureType.osElementName.c_str(),
     998             :                                         oFeatureType.osElementValue.c_str());
     999             :                                 else
    1000          25 :                                     pszElementToFind = CPLSPrintf(
    1001             :                                         "<%s",
    1002             :                                         oFeatureType.osElementName.c_str());
    1003             :                             }
    1004             : 
    1005             :                             // Case sensitive test since in a CadastralParcel
    1006             :                             // feature there is a property basicPropertyUnit
    1007             :                             // xlink, not to be confused with a top-level
    1008             :                             // BasicPropertyUnit feature.
    1009          40 :                             if (osHeader.find(pszElementToFind) !=
    1010             :                                 std::string::npos)
    1011             :                             {
    1012          11 :                                 if (!oFeatureType.osSchemaLocation.empty())
    1013             :                                 {
    1014             :                                     osXSDFilename =
    1015           1 :                                         oFeatureType.osSchemaLocation;
    1016           1 :                                     if (STARTS_WITH(osXSDFilename, "http://") ||
    1017           1 :                                         STARTS_WITH(osXSDFilename,
    1018           2 :                                                     "https://") ||
    1019           1 :                                         VSIStatExL(osXSDFilename, &sXSDStatBuf,
    1020             :                                                    VSI_STAT_EXISTS_FLAG) == 0)
    1021             :                                     {
    1022           1 :                                         bHasFoundXSD = true;
    1023           1 :                                         bHaveSchema = true;
    1024           1 :                                         CPLDebug(
    1025             :                                             "GML",
    1026             :                                             "Found %s for %s:%s in registry",
    1027             :                                             osXSDFilename.c_str(),
    1028             :                                             oNamespace.osPrefix.c_str(),
    1029             :                                             oFeatureType.osElementName.c_str());
    1030             :                                     }
    1031             :                                     else
    1032             :                                     {
    1033           0 :                                         CPLDebug("GML", "Cannot open %s",
    1034             :                                                  osXSDFilename.c_str());
    1035             :                                     }
    1036             :                                 }
    1037             :                                 else
    1038             :                                 {
    1039          10 :                                     bHaveSchema = poReader->LoadClasses(
    1040          10 :                                         oFeatureType.osGFSSchemaLocation);
    1041          10 :                                     if (bHaveSchema)
    1042             :                                     {
    1043          10 :                                         CPLDebug(
    1044             :                                             "GML",
    1045             :                                             "Found %s for %s:%s in registry",
    1046             :                                             oFeatureType.osGFSSchemaLocation
    1047             :                                                 .c_str(),
    1048             :                                             oNamespace.osPrefix.c_str(),
    1049             :                                             oFeatureType.osElementName.c_str());
    1050             :                                     }
    1051             :                                 }
    1052          11 :                                 break;
    1053             :                             }
    1054             :                         }
    1055          11 :                         break;
    1056             :                     }
    1057             :                 }
    1058             :             }
    1059             :         }
    1060             : 
    1061             :         /* For WFS, try to fetch the application schema */
    1062         396 :         if (bIsWFS && !bHaveSchema && pszSchemaLocation != nullptr &&
    1063         142 :             (pszSchemaLocation[0] == '\'' || pszSchemaLocation[0] == '"') &&
    1064         142 :             strchr(pszSchemaLocation + 1, pszSchemaLocation[0]) != nullptr)
    1065             :         {
    1066         142 :             char *pszSchemaLocationTmp1 = CPLStrdup(pszSchemaLocation + 1);
    1067         142 :             int nTruncLen = static_cast<int>(
    1068         142 :                 strchr(pszSchemaLocation + 1, pszSchemaLocation[0]) -
    1069         142 :                 (pszSchemaLocation + 1));
    1070         142 :             pszSchemaLocationTmp1[nTruncLen] = '\0';
    1071             :             char *pszSchemaLocationTmp2 =
    1072         142 :                 CPLUnescapeString(pszSchemaLocationTmp1, nullptr, CPLES_XML);
    1073             :             CPLString osEscaped =
    1074         284 :                 ReplaceSpaceByPct20IfNeeded(pszSchemaLocationTmp2);
    1075         142 :             CPLFree(pszSchemaLocationTmp2);
    1076         142 :             pszSchemaLocationTmp2 = CPLStrdup(osEscaped);
    1077         142 :             if (pszSchemaLocationTmp2)
    1078             :             {
    1079             :                 // pszSchemaLocationTmp2 is of the form:
    1080             :                 // http://namespace1 http://namespace1_schema_location
    1081             :                 // http://namespace2 http://namespace1_schema_location2 So we
    1082             :                 // try to find http://namespace1_schema_location that contains
    1083             :                 // hints that it is the WFS application */ schema, i.e. if it
    1084             :                 // contains typename= and request=DescribeFeatureType.
    1085             :                 char **papszTokens =
    1086         142 :                     CSLTokenizeString2(pszSchemaLocationTmp2, " \r\n", 0);
    1087         142 :                 int nTokens = CSLCount(papszTokens);
    1088         142 :                 if ((nTokens % 2) == 0)
    1089             :                 {
    1090         302 :                     for (int i = 0; i < nTokens; i += 2)
    1091             :                     {
    1092         286 :                         const char *pszEscapedURL = papszTokens[i + 1];
    1093         286 :                         char *pszLocation = CPLUnescapeString(
    1094             :                             pszEscapedURL, nullptr, CPLES_URL);
    1095         286 :                         CPLString osLocation = pszLocation;
    1096         286 :                         CPLFree(pszLocation);
    1097         286 :                         if (osLocation.ifind("typename=") !=
    1098         412 :                                 std::string::npos &&
    1099         126 :                             osLocation.ifind("request=DescribeFeatureType") !=
    1100             :                                 std::string::npos)
    1101             :                         {
    1102             :                             CPLString osTypeName =
    1103         252 :                                 CPLURLGetValue(osLocation, "typename");
    1104             :                             papszTypeNames =
    1105         126 :                                 CSLTokenizeString2(osTypeName, ",", 0);
    1106             : 
    1107             :                             // Old non-documented way
    1108             :                             const char *pszGML_DOWNLOAD_WFS_SCHEMA =
    1109         126 :                                 CPLGetConfigOption("GML_DOWNLOAD_WFS_SCHEMA",
    1110             :                                                    nullptr);
    1111         126 :                             if (pszGML_DOWNLOAD_WFS_SCHEMA)
    1112             :                             {
    1113           0 :                                 CPLError(
    1114             :                                     CE_Warning, CPLE_AppDefined,
    1115             :                                     "Configuration option "
    1116             :                                     "GML_DOWNLOAD_WFS_SCHEMA is deprecated. "
    1117             :                                     "Please use GML_DOWNLOAD_SCHEMA instead of "
    1118             :                                     "the DOWNLOAD_SCHEMA open option");
    1119             :                             }
    1120             :                             else
    1121             :                             {
    1122         126 :                                 pszGML_DOWNLOAD_WFS_SCHEMA = "YES";
    1123             :                             }
    1124         134 :                             if (!bHasFoundXSD && CPLHTTPEnabled() &&
    1125           8 :                                 CPLFetchBool(poOpenInfo->papszOpenOptions,
    1126             :                                              "DOWNLOAD_SCHEMA",
    1127           8 :                                              CPLTestBool(CPLGetConfigOption(
    1128             :                                                  "GML_DOWNLOAD_SCHEMA",
    1129             :                                                  pszGML_DOWNLOAD_WFS_SCHEMA))))
    1130             :                             {
    1131             :                                 CPLHTTPResult *psResult =
    1132           8 :                                     CPLHTTPFetch(pszEscapedURL, nullptr);
    1133           8 :                                 if (psResult)
    1134             :                                 {
    1135           8 :                                     if (psResult->nStatus == 0 &&
    1136           7 :                                         psResult->pabyData != nullptr)
    1137             :                                     {
    1138           7 :                                         bHasFoundXSD = true;
    1139           7 :                                         m_bUnlinkXSDFilename = true;
    1140             :                                         osXSDFilename =
    1141             :                                             VSIMemGenerateHiddenFilename(
    1142           7 :                                                 "tmp_ogr_gml.xsd");
    1143           7 :                                         VSILFILE *fpMem = VSIFileFromMemBuffer(
    1144             :                                             osXSDFilename, psResult->pabyData,
    1145           7 :                                             psResult->nDataLen, TRUE);
    1146           7 :                                         VSIFCloseL(fpMem);
    1147           7 :                                         psResult->pabyData = nullptr;
    1148             :                                     }
    1149           8 :                                     CPLHTTPDestroyResult(psResult);
    1150             :                                 }
    1151             :                             }
    1152         126 :                             break;
    1153             :                         }
    1154             :                     }
    1155             :                 }
    1156         142 :                 CSLDestroy(papszTokens);
    1157             :             }
    1158         142 :             CPLFree(pszSchemaLocationTmp2);
    1159         142 :             CPLFree(pszSchemaLocationTmp1);
    1160             :         }
    1161             : 
    1162         396 :         bool bHasFeatureProperties = false;
    1163         396 :         if (bHasFoundXSD)
    1164             :         {
    1165         566 :             std::vector<GMLFeatureClass *> aosClasses;
    1166         566 :             bool bUseSchemaImports = CPLFetchBool(
    1167         283 :                 poOpenInfo->papszOpenOptions, "USE_SCHEMA_IMPORT",
    1168         283 :                 CPLTestBool(CPLGetConfigOption("GML_USE_SCHEMA_IMPORT", "NO")));
    1169         283 :             bool bFullyUnderstood = false;
    1170         283 :             bHaveSchema = GMLParseXSD(osXSDFilename, bUseSchemaImports,
    1171             :                                       aosClasses, bFullyUnderstood);
    1172             : 
    1173         283 :             if (bHaveSchema && !bFullyUnderstood && bIsWFSJointLayer)
    1174             :             {
    1175           1 :                 CPLDebug("GML", "Schema found, but only partially understood. "
    1176             :                                 "Cannot be used in a WFS join context");
    1177             : 
    1178             :                 std::vector<GMLFeatureClass *>::const_iterator oIter =
    1179           1 :                     aosClasses.begin();
    1180             :                 std::vector<GMLFeatureClass *>::const_iterator oEndIter =
    1181           1 :                     aosClasses.end();
    1182           2 :                 while (oIter != oEndIter)
    1183             :                 {
    1184           1 :                     GMLFeatureClass *poClass = *oIter;
    1185             : 
    1186           1 :                     delete poClass;
    1187           1 :                     ++oIter;
    1188             :                 }
    1189           1 :                 aosClasses.resize(0);
    1190           1 :                 bHaveSchema = false;
    1191             :             }
    1192             : 
    1193         283 :             if (bHaveSchema)
    1194             :             {
    1195         273 :                 CPLDebug("GML", "Using %s", osXSDFilename.c_str());
    1196             :                 std::vector<GMLFeatureClass *>::const_iterator oIter =
    1197         273 :                     aosClasses.begin();
    1198             :                 std::vector<GMLFeatureClass *>::const_iterator oEndIter =
    1199         273 :                     aosClasses.end();
    1200         658 :                 while (oIter != oEndIter)
    1201             :                 {
    1202         386 :                     GMLFeatureClass *poClass = *oIter;
    1203             : 
    1204         386 :                     if (poClass->HasFeatureProperties())
    1205             :                     {
    1206           1 :                         bHasFeatureProperties = true;
    1207           1 :                         break;
    1208             :                     }
    1209         385 :                     ++oIter;
    1210             :                 }
    1211             : 
    1212         273 :                 oIter = aosClasses.begin();
    1213         661 :                 while (oIter != oEndIter)
    1214             :                 {
    1215         388 :                     GMLFeatureClass *poClass = *oIter;
    1216         388 :                     ++oIter;
    1217             : 
    1218             :                     // We have no way of knowing if the geometry type is 25D
    1219             :                     // when examining the xsd only, so if there was a hint
    1220             :                     // it is, we force to 25D.
    1221         388 :                     if (bHas3D && poClass->GetGeometryPropertyCount() == 1)
    1222             :                     {
    1223          35 :                         poClass->GetGeometryProperty(0)->SetType(
    1224             :                             wkbSetZ(static_cast<OGRwkbGeometryType>(
    1225             :                                 poClass->GetGeometryProperty(0)->GetType())));
    1226             :                     }
    1227             : 
    1228         388 :                     bool bAddClass = true;
    1229             :                     // If typenames are declared, only register the matching
    1230             :                     // classes, in case the XSD contains more layers, but not if
    1231             :                     // feature classes contain feature properties, in which case
    1232             :                     // we will have embedded features that will be reported as
    1233             :                     // top-level features.
    1234         388 :                     if (papszTypeNames != nullptr && !bHasFeatureProperties)
    1235             :                     {
    1236         178 :                         bAddClass = false;
    1237         178 :                         char **papszIter = papszTypeNames;
    1238         416 :                         while (*papszIter && !bAddClass)
    1239             :                         {
    1240         238 :                             const char *pszTypeName = *papszIter;
    1241         238 :                             if (strcmp(pszTypeName, poClass->GetName()) == 0)
    1242         177 :                                 bAddClass = true;
    1243         238 :                             papszIter++;
    1244             :                         }
    1245             : 
    1246             :                         // Retry by removing prefixes.
    1247         178 :                         if (!bAddClass)
    1248             :                         {
    1249           1 :                             papszIter = papszTypeNames;
    1250           2 :                             while (*papszIter && !bAddClass)
    1251             :                             {
    1252           1 :                                 const char *pszTypeName = *papszIter;
    1253           1 :                                 const char *pszColon = strchr(pszTypeName, ':');
    1254           1 :                                 if (pszColon)
    1255             :                                 {
    1256           1 :                                     pszTypeName = pszColon + 1;
    1257           1 :                                     if (strcmp(pszTypeName,
    1258           1 :                                                poClass->GetName()) == 0)
    1259             :                                     {
    1260           1 :                                         poClass->SetName(pszTypeName);
    1261           1 :                                         bAddClass = true;
    1262             :                                     }
    1263             :                                 }
    1264           1 :                                 papszIter++;
    1265             :                             }
    1266             :                         }
    1267             :                     }
    1268             : 
    1269         776 :                     if (bAddClass &&
    1270         388 :                         poReader->GetClass(poClass->GetName()) == nullptr)
    1271             :                     {
    1272         388 :                         poReader->AddClass(poClass);
    1273             :                     }
    1274             :                     else
    1275           0 :                         delete poClass;
    1276             :                 }
    1277             : 
    1278         273 :                 poReader->SetClassListLocked(true);
    1279             :             }
    1280             :         }
    1281             : 
    1282         396 :         if (bHaveSchema && bIsWFS)
    1283             :         {
    1284         136 :             if (bIsWFSJointLayer)
    1285             :             {
    1286          47 :                 BuildJointClassFromXSD();
    1287             :             }
    1288             : 
    1289             :             // For WFS, we can assume sequential layers.
    1290         155 :             if (poReader->GetClassCount() > 1 && pszReadMode == nullptr &&
    1291          19 :                 !bHasFeatureProperties)
    1292             :             {
    1293          19 :                 CPLDebug("GML",
    1294             :                          "WFS output. Using SEQUENTIAL_LAYERS read mode");
    1295          19 :                 eReadMode = SEQUENTIAL_LAYERS;
    1296             :             }
    1297             :             // Sometimes the returned schema contains only <xs:include> that we
    1298             :             // don't resolve so ignore it.
    1299         117 :             else if (poReader->GetClassCount() == 0)
    1300           0 :                 bHaveSchema = false;
    1301             :         }
    1302             : 
    1303         396 :         CSLDestroy(papszTypeNames);
    1304             :     }
    1305             : 
    1306             :     // Japan Fundamental Geospatial Data (FGD)
    1307         446 :     if (strstr(szPtr, "http://fgd.gsi.go.jp/spec/2008/FGD_GMLSchema"))
    1308             :     {
    1309           4 :         if (ExtractSRSName(szPtr, szSRSName, sizeof(szSRSName)))
    1310             :         {
    1311           8 :             CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
    1312           8 :             OGRSpatialReference oSRS;
    1313           4 :             if (oSRS.SetFromUserInput(
    1314             :                     szSRSName,
    1315             :                     OGRSpatialReference::
    1316           4 :                         SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE)
    1317             :             {
    1318           4 :                 bUseGlobalSRSName = true;
    1319           8 :                 for (int i = 0; i < poReader->GetClassCount(); ++i)
    1320             :                 {
    1321           4 :                     poReader->GetClass(i)->SetSRSName(szSRSName);
    1322             :                 }
    1323             :             }
    1324             :         }
    1325             :     }
    1326             : 
    1327             :     // Force a first pass to establish the schema.  Eventually we will have
    1328             :     // mechanisms for remembering the schema and related information.
    1329             :     const char *pszForceSRSDetection =
    1330         446 :         CSLFetchNameValue(poOpenInfo->papszOpenOptions, "FORCE_SRS_DETECTION");
    1331         455 :     if (!bHaveSchema ||
    1332           9 :         (pszForceSRSDetection && CPLTestBool(pszForceSRSDetection)))
    1333             :     {
    1334         122 :         bool bOnlyDetectSRS = bHaveSchema;
    1335         122 :         if (!poReader->PrescanForSchema(true, bOnlyDetectSRS))
    1336             :         {
    1337             :             // Assume an error was reported.
    1338           0 :             return false;
    1339             :         }
    1340         122 :         if (!bHaveSchema)
    1341             :         {
    1342         113 :             if (bIsWFSJointLayer && poReader->GetClassCount() == 1)
    1343             :             {
    1344           2 :                 BuildJointClassFromScannedSchema();
    1345             :             }
    1346             : 
    1347         113 :             if (bHasFoundXSD)
    1348             :             {
    1349          10 :                 CPLDebug("GML", "Generating %s file, ignoring %s",
    1350             :                          osGFSFilename.c_str(), osXSDFilename.c_str());
    1351             :             }
    1352             :         }
    1353             :     }
    1354             : 
    1355         446 :     if (poReader->GetClassCount() > 1 && poReader->IsSequentialLayers() &&
    1356             :         pszReadMode == nullptr)
    1357             :     {
    1358          27 :         CPLDebug("GML",
    1359             :                  "Layers are monoblock. Using SEQUENTIAL_LAYERS read mode");
    1360          27 :         eReadMode = SEQUENTIAL_LAYERS;
    1361             :     }
    1362             : 
    1363         446 :     if (!DealWithOgrSchemaOpenOption(poOpenInfo))
    1364             :     {
    1365          10 :         return false;
    1366             :     }
    1367             : 
    1368             :     // Save the schema file if possible.  Don't make a fuss if we
    1369             :     // can't.  It could be read-only directory or something.
    1370             :     const char *pszWriteGFS =
    1371         436 :         CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "WRITE_GFS", "AUTO");
    1372         436 :     bool bWriteGFS = false;
    1373         436 :     if (EQUAL(pszWriteGFS, "AUTO"))
    1374             :     {
    1375         111 :         if (!bHaveSchema && !poReader->HasStoppedParsing() &&
    1376         651 :             VSIIsLocal(pszFilename) &&
    1377         107 :             VSISupportsSequentialWrite(pszFilename, false))
    1378             :         {
    1379             :             VSIStatBufL sGFSStatBuf;
    1380         107 :             if (VSIStatExL(osGFSFilename, &sGFSStatBuf, VSI_STAT_EXISTS_FLAG) !=
    1381             :                 0)
    1382             :             {
    1383         102 :                 bWriteGFS = true;
    1384             :             }
    1385             :             else
    1386             :             {
    1387           5 :                 CPLDebug("GML", "Not saving %s file: already exists.",
    1388             :                          osGFSFilename.c_str());
    1389             :             }
    1390             :         }
    1391             :     }
    1392           3 :     else if (CPLTestBool(pszWriteGFS))
    1393             :     {
    1394           1 :         if (bHaveSchema || !poReader->HasStoppedParsing())
    1395             :         {
    1396           1 :             bWriteGFS = true;
    1397             :         }
    1398             :         else
    1399             :         {
    1400           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    1401             :                      "GFS file saving asked, but cannot be done");
    1402             :         }
    1403             :     }
    1404             : 
    1405         436 :     if (bWriteGFS)
    1406             :     {
    1407         103 :         if (!poReader->SaveClasses(osGFSFilename))
    1408             :         {
    1409           0 :             if (CPLTestBool(pszWriteGFS))
    1410             :             {
    1411           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1412             :                          "GFS file saving asked, but failed");
    1413             :             }
    1414             :             else
    1415             :             {
    1416           0 :                 CPLDebug("GML", "Not saving %s file: can't be created.",
    1417             :                          osGFSFilename.c_str());
    1418             :             }
    1419             :         }
    1420             :     }
    1421             : 
    1422             :     // Translate the GMLFeatureClasses into layers.
    1423         436 :     papoLayers = static_cast<OGRLayer **>(
    1424         436 :         CPLCalloc(sizeof(OGRLayer *), poReader->GetClassCount()));
    1425         436 :     nLayers = 0;
    1426             : 
    1427         436 :     if (poReader->GetClassCount() == 1 && nNumberOfFeatures != 0)
    1428             :     {
    1429         118 :         GMLFeatureClass *poClass = poReader->GetClass(0);
    1430         118 :         GIntBig nFeatureCount = poClass->GetFeatureCount();
    1431         118 :         if (nFeatureCount < 0)
    1432             :         {
    1433         106 :             poClass->SetFeatureCount(nNumberOfFeatures);
    1434             :         }
    1435          12 :         else if (nFeatureCount != nNumberOfFeatures)
    1436             :         {
    1437           0 :             CPLDebug("GML", "Feature count in header, "
    1438             :                             "and actual feature count don't match");
    1439             :         }
    1440             :     }
    1441             : 
    1442         436 :     if (bIsWFS && poReader->GetClassCount() == 1)
    1443         138 :         bUseGlobalSRSName = true;
    1444             : 
    1445        1015 :     while (nLayers < poReader->GetClassCount())
    1446             :     {
    1447         579 :         papoLayers[nLayers] = TranslateGMLSchema(poReader->GetClass(nLayers));
    1448         579 :         nLayers++;
    1449             :     }
    1450             : 
    1451             :     // Warn if we have geometry columns without known CRS due to only using
    1452             :     // the .xsd
    1453         436 :     if (bHaveSchema && pszForceSRSDetection == nullptr)
    1454             :     {
    1455         314 :         bool bExitLoop = false;
    1456         673 :         for (int i = 0; !bExitLoop && i < nLayers; ++i)
    1457             :         {
    1458         359 :             const auto poLayer = papoLayers[i];
    1459         359 :             const auto poLayerDefn = poLayer->GetLayerDefn();
    1460         359 :             const auto nGeomFieldCount = poLayerDefn->GetGeomFieldCount();
    1461         494 :             for (int j = 0; j < nGeomFieldCount; ++j)
    1462             :             {
    1463         374 :                 if (poLayerDefn->GetGeomFieldDefn(j)->GetSpatialRef() ==
    1464             :                     nullptr)
    1465             :                 {
    1466         239 :                     bExitLoop = true;
    1467         239 :                     break;
    1468             :                 }
    1469             :             }
    1470             :         }
    1471         314 :         if (bExitLoop)
    1472             :         {
    1473         239 :             CPLDebug("GML",
    1474             :                      "Geometry fields without known CRS have been detected. "
    1475             :                      "You may want to specify the FORCE_SRS_DETECTION open "
    1476             :                      "option to YES.");
    1477             :         }
    1478             :     }
    1479             : 
    1480         436 :     return true;
    1481             : }
    1482             : 
    1483             : /************************************************************************/
    1484             : /*                          BuildJointClassFromXSD()                    */
    1485             : /************************************************************************/
    1486             : 
    1487          47 : void OGRGMLDataSource::BuildJointClassFromXSD()
    1488             : {
    1489          94 :     CPLString osJointClassName = "join";
    1490         141 :     for (int i = 0; i < poReader->GetClassCount(); i++)
    1491             :     {
    1492          94 :         osJointClassName += "_";
    1493          94 :         osJointClassName += poReader->GetClass(i)->GetName();
    1494             :     }
    1495          47 :     GMLFeatureClass *poJointClass = new GMLFeatureClass(osJointClassName);
    1496          47 :     poJointClass->SetElementName("Tuple");
    1497         141 :     for (int i = 0; i < poReader->GetClassCount(); i++)
    1498             :     {
    1499          94 :         GMLFeatureClass *poClass = poReader->GetClass(i);
    1500             : 
    1501             :         {
    1502         188 :             CPLString osPropertyName;
    1503          94 :             osPropertyName.Printf("%s.%s", poClass->GetName(), "gml_id");
    1504             :             GMLPropertyDefn *poNewProperty =
    1505          94 :                 new GMLPropertyDefn(osPropertyName);
    1506         188 :             CPLString osSrcElement;
    1507          94 :             osSrcElement.Printf("member|%s@id", poClass->GetName());
    1508          94 :             poNewProperty->SetSrcElement(osSrcElement);
    1509          94 :             poNewProperty->SetType(GMLPT_String);
    1510          94 :             poJointClass->AddProperty(poNewProperty);
    1511             :         }
    1512             : 
    1513         200 :         for (int iField = 0; iField < poClass->GetPropertyCount(); iField++)
    1514             :         {
    1515         106 :             GMLPropertyDefn *poProperty = poClass->GetProperty(iField);
    1516         212 :             CPLString osPropertyName;
    1517             :             osPropertyName.Printf("%s.%s", poClass->GetName(),
    1518         106 :                                   poProperty->GetName());
    1519             :             GMLPropertyDefn *poNewProperty =
    1520         106 :                 new GMLPropertyDefn(osPropertyName);
    1521             : 
    1522         106 :             poNewProperty->SetType(poProperty->GetType());
    1523         212 :             CPLString osSrcElement;
    1524             :             osSrcElement.Printf("member|%s|%s", poClass->GetName(),
    1525         106 :                                 poProperty->GetSrcElement());
    1526         106 :             poNewProperty->SetSrcElement(osSrcElement);
    1527         106 :             poNewProperty->SetWidth(poProperty->GetWidth());
    1528         106 :             poNewProperty->SetPrecision(poProperty->GetPrecision());
    1529         106 :             poNewProperty->SetNullable(poProperty->IsNullable());
    1530             : 
    1531         106 :             poJointClass->AddProperty(poNewProperty);
    1532             :         }
    1533         188 :         for (int iField = 0; iField < poClass->GetGeometryPropertyCount();
    1534             :              iField++)
    1535             :         {
    1536             :             GMLGeometryPropertyDefn *poProperty =
    1537          94 :                 poClass->GetGeometryProperty(iField);
    1538         188 :             CPLString osPropertyName;
    1539             :             osPropertyName.Printf("%s.%s", poClass->GetName(),
    1540          94 :                                   poProperty->GetName());
    1541         188 :             CPLString osSrcElement;
    1542             :             osSrcElement.Printf("member|%s|%s", poClass->GetName(),
    1543          94 :                                 poProperty->GetSrcElement());
    1544             :             GMLGeometryPropertyDefn *poNewProperty =
    1545             :                 new GMLGeometryPropertyDefn(osPropertyName, osSrcElement,
    1546          94 :                                             poProperty->GetType(), -1,
    1547         188 :                                             poProperty->IsNullable());
    1548          94 :             poJointClass->AddGeometryProperty(poNewProperty);
    1549             :         }
    1550             :     }
    1551          47 :     poJointClass->SetSchemaLocked(true);
    1552             : 
    1553          47 :     poReader->ClearClasses();
    1554          47 :     poReader->AddClass(poJointClass);
    1555          47 : }
    1556             : 
    1557             : /************************************************************************/
    1558             : /*                   BuildJointClassFromScannedSchema()                 */
    1559             : /************************************************************************/
    1560             : 
    1561           2 : void OGRGMLDataSource::BuildJointClassFromScannedSchema()
    1562             : {
    1563             :     // Make sure that all properties of a same base feature type are
    1564             :     // consecutive. If not, reorder.
    1565           4 :     std::vector<std::vector<GMLPropertyDefn *>> aapoProps;
    1566           2 :     GMLFeatureClass *poClass = poReader->GetClass(0);
    1567           4 :     CPLString osJointClassName = "join";
    1568             : 
    1569          14 :     for (int iField = 0; iField < poClass->GetPropertyCount(); iField++)
    1570             :     {
    1571          12 :         GMLPropertyDefn *poProp = poClass->GetProperty(iField);
    1572          24 :         CPLString osPrefix(poProp->GetName());
    1573          12 :         size_t iPos = osPrefix.find('.');
    1574          12 :         if (iPos != std::string::npos)
    1575          12 :             osPrefix.resize(iPos);
    1576          12 :         int iSubClass = 0;  // Used after for.
    1577          18 :         for (; iSubClass < static_cast<int>(aapoProps.size()); iSubClass++)
    1578             :         {
    1579          14 :             CPLString osPrefixClass(aapoProps[iSubClass][0]->GetName());
    1580          14 :             iPos = osPrefixClass.find('.');
    1581          14 :             if (iPos != std::string::npos)
    1582          14 :                 osPrefixClass.resize(iPos);
    1583          14 :             if (osPrefix == osPrefixClass)
    1584           8 :                 break;
    1585             :         }
    1586          12 :         if (iSubClass == static_cast<int>(aapoProps.size()))
    1587             :         {
    1588           4 :             osJointClassName += "_";
    1589           4 :             osJointClassName += osPrefix;
    1590           4 :             aapoProps.push_back(std::vector<GMLPropertyDefn *>());
    1591             :         }
    1592          12 :         aapoProps[iSubClass].push_back(poProp);
    1593             :     }
    1594           2 :     poClass->SetElementName(poClass->GetName());
    1595           2 :     poClass->SetName(osJointClassName);
    1596             : 
    1597           2 :     poClass->StealProperties();
    1598             :     std::vector<std::pair<CPLString, std::vector<GMLGeometryPropertyDefn *>>>
    1599           4 :         aapoGeomProps;
    1600           6 :     for (int iSubClass = 0; iSubClass < static_cast<int>(aapoProps.size());
    1601             :          iSubClass++)
    1602             :     {
    1603           8 :         CPLString osPrefixClass(aapoProps[iSubClass][0]->GetName());
    1604           4 :         size_t iPos = osPrefixClass.find('.');
    1605           4 :         if (iPos != std::string::npos)
    1606           4 :             osPrefixClass.resize(iPos);
    1607             :         aapoGeomProps.emplace_back(
    1608           4 :             std::pair(osPrefixClass, std::vector<GMLGeometryPropertyDefn *>()));
    1609          16 :         for (int iField = 0;
    1610          16 :              iField < static_cast<int>(aapoProps[iSubClass].size()); iField++)
    1611             :         {
    1612          12 :             poClass->AddProperty(aapoProps[iSubClass][iField]);
    1613             :         }
    1614             :     }
    1615           2 :     aapoProps.resize(0);
    1616             : 
    1617             :     // Reorder geometry fields too
    1618           6 :     for (int iField = 0; iField < poClass->GetGeometryPropertyCount(); iField++)
    1619             :     {
    1620           4 :         GMLGeometryPropertyDefn *poProp = poClass->GetGeometryProperty(iField);
    1621           8 :         CPLString osPrefix(poProp->GetName());
    1622           4 :         size_t iPos = osPrefix.find('.');
    1623           4 :         if (iPos != std::string::npos)
    1624           4 :             osPrefix.resize(iPos);
    1625           4 :         int iSubClass = 0;  // Used after for.
    1626           6 :         for (; iSubClass < static_cast<int>(aapoGeomProps.size()); iSubClass++)
    1627             :         {
    1628           6 :             if (osPrefix == aapoGeomProps[iSubClass].first)
    1629           4 :                 break;
    1630             :         }
    1631           4 :         if (iSubClass == static_cast<int>(aapoGeomProps.size()))
    1632             :             aapoGeomProps.emplace_back(
    1633           0 :                 std::pair(osPrefix, std::vector<GMLGeometryPropertyDefn *>()));
    1634           4 :         aapoGeomProps[iSubClass].second.push_back(poProp);
    1635             :     }
    1636           2 :     poClass->StealGeometryProperties();
    1637           6 :     for (int iSubClass = 0; iSubClass < static_cast<int>(aapoGeomProps.size());
    1638             :          iSubClass++)
    1639             :     {
    1640           8 :         for (int iField = 0;
    1641           8 :              iField < static_cast<int>(aapoGeomProps[iSubClass].second.size());
    1642             :              iField++)
    1643             :         {
    1644           4 :             poClass->AddGeometryProperty(
    1645           4 :                 aapoGeomProps[iSubClass].second[iField]);
    1646             :         }
    1647             :     }
    1648           2 : }
    1649             : 
    1650             : /************************************************************************/
    1651             : /*                         TranslateGMLSchema()                         */
    1652             : /************************************************************************/
    1653             : 
    1654         579 : OGRLayer *OGRGMLDataSource::TranslateGMLSchema(GMLFeatureClass *poClass)
    1655             : 
    1656             : {
    1657             :     // Create an empty layer.
    1658         579 :     const char *pszSRSName = poClass->GetSRSName();
    1659         579 :     OGRSpatialReference *poSRS = nullptr;
    1660         579 :     if (pszSRSName)
    1661             :     {
    1662         133 :         poSRS = new OGRSpatialReference();
    1663         133 :         poSRS->SetAxisMappingStrategy(m_bInvertAxisOrderIfLatLong
    1664             :                                           ? OAMS_TRADITIONAL_GIS_ORDER
    1665             :                                           : OAMS_AUTHORITY_COMPLIANT);
    1666         133 :         if (poSRS->SetFromUserInput(
    1667             :                 pszSRSName,
    1668         133 :                 OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
    1669             :             OGRERR_NONE)
    1670             :         {
    1671           0 :             delete poSRS;
    1672           0 :             poSRS = nullptr;
    1673             :         }
    1674             :     }
    1675             :     else
    1676             :     {
    1677         446 :         pszSRSName = GetGlobalSRSName();
    1678             : 
    1679         446 :         if (pszSRSName && GML_IsLegitSRSName(pszSRSName))
    1680             :         {
    1681          35 :             poSRS = new OGRSpatialReference();
    1682          35 :             poSRS->SetAxisMappingStrategy(m_bInvertAxisOrderIfLatLong
    1683             :                                               ? OAMS_TRADITIONAL_GIS_ORDER
    1684             :                                               : OAMS_AUTHORITY_COMPLIANT);
    1685          35 :             if (poSRS->SetFromUserInput(
    1686             :                     pszSRSName,
    1687             :                     OGRSpatialReference::
    1688          35 :                         SET_FROM_USER_INPUT_LIMITATIONS_get()) != OGRERR_NONE)
    1689             :             {
    1690           0 :                 delete poSRS;
    1691           0 :                 poSRS = nullptr;
    1692             :             }
    1693             : 
    1694          70 :             if (poSRS != nullptr && m_bInvertAxisOrderIfLatLong &&
    1695          35 :                 GML_IsSRSLatLongOrder(pszSRSName))
    1696             :             {
    1697          23 :                 if (!poClass->HasExtents() && sBoundingRect.IsInit())
    1698             :                 {
    1699          23 :                     poClass->SetExtents(sBoundingRect.MinY, sBoundingRect.MaxY,
    1700             :                                         sBoundingRect.MinX, sBoundingRect.MaxX);
    1701             :                 }
    1702             :             }
    1703             :         }
    1704             : 
    1705         446 :         if (!poClass->HasExtents() && sBoundingRect.IsInit())
    1706             :         {
    1707          12 :             poClass->SetExtents(sBoundingRect.MinX, sBoundingRect.MaxX,
    1708             :                                 sBoundingRect.MinY, sBoundingRect.MaxY);
    1709             :         }
    1710             :     }
    1711             : 
    1712             :     // Report a COMPD_CS only if GML_REPORT_COMPD_CS is explicitly set to TRUE.
    1713         579 :     if (poSRS != nullptr && poSRS->IsCompound())
    1714             :     {
    1715             :         const char *pszReportCompdCS =
    1716           8 :             CPLGetConfigOption("GML_REPORT_COMPD_CS", nullptr);
    1717           8 :         if (pszReportCompdCS == nullptr)
    1718             :         {
    1719           8 :             CPLDebug("GML", "Compound CRS detected but only horizontal part "
    1720             :                             "will be reported. Set the GML_REPORT_COMPD_CS=YES "
    1721             :                             "configuration option to get the Compound CRS");
    1722           8 :             pszReportCompdCS = "FALSE";
    1723             :         }
    1724           8 :         if (!CPLTestBool(pszReportCompdCS))
    1725             :         {
    1726           8 :             OGR_SRSNode *poCOMPD_CS = poSRS->GetAttrNode("COMPD_CS");
    1727           8 :             if (poCOMPD_CS != nullptr)
    1728             :             {
    1729           8 :                 OGR_SRSNode *poCandidateRoot = poCOMPD_CS->GetNode("PROJCS");
    1730           8 :                 if (poCandidateRoot == nullptr)
    1731           1 :                     poCandidateRoot = poCOMPD_CS->GetNode("GEOGCS");
    1732           8 :                 if (poCandidateRoot != nullptr)
    1733             :                 {
    1734           8 :                     poSRS->SetRoot(poCandidateRoot->Clone());
    1735             :                 }
    1736             :             }
    1737             :         }
    1738             :     }
    1739             : 
    1740         579 :     OGRLayer *poLayer = new OGRGMLLayer(poClass->GetName(), false, this);
    1741             : 
    1742             :     // Added attributes (properties).
    1743         579 :     if (bExposeGMLId)
    1744             :     {
    1745         868 :         OGRFieldDefn oField("gml_id", OFTString);
    1746         434 :         oField.SetNullable(FALSE);
    1747         434 :         poLayer->GetLayerDefn()->AddFieldDefn(&oField);
    1748             :     }
    1749         145 :     else if (bExposeFid)
    1750             :     {
    1751         110 :         OGRFieldDefn oField("fid", OFTString);
    1752          55 :         oField.SetNullable(FALSE);
    1753          55 :         poLayer->GetLayerDefn()->AddFieldDefn(&oField);
    1754             :     }
    1755             : 
    1756        1217 :     for (int iField = 0; iField < poClass->GetGeometryPropertyCount(); iField++)
    1757             :     {
    1758             :         GMLGeometryPropertyDefn *poProperty =
    1759         638 :             poClass->GetGeometryProperty(iField);
    1760             : 
    1761             :         // Patch wrong .gfs file produced by earlier versions
    1762         638 :         if (poProperty->GetType() == wkbPolyhedralSurface &&
    1763           0 :             strcmp(poProperty->GetName(), "lod2Solid") == 0)
    1764             :         {
    1765           0 :             poProperty->SetType(wkbPolyhedralSurfaceZ);
    1766             :         }
    1767             : 
    1768        1276 :         OGRGeomFieldDefn oField(poProperty->GetName(), poProperty->GetType());
    1769        1082 :         if (poClass->GetGeometryPropertyCount() == 1 &&
    1770         444 :             poClass->GetFeatureCount() == 0)
    1771             :         {
    1772           0 :             oField.SetType(wkbUnknown);
    1773             :         }
    1774             : 
    1775         638 :         const auto &osSRSName = poProperty->GetSRSName();
    1776         638 :         if (!osSRSName.empty())
    1777             :         {
    1778          30 :             OGRSpatialReference *poSRS2 = new OGRSpatialReference();
    1779          30 :             poSRS2->SetAxisMappingStrategy(m_bInvertAxisOrderIfLatLong
    1780             :                                                ? OAMS_TRADITIONAL_GIS_ORDER
    1781             :                                                : OAMS_AUTHORITY_COMPLIANT);
    1782          30 :             if (poSRS2->SetFromUserInput(
    1783             :                     osSRSName.c_str(),
    1784             :                     OGRSpatialReference::
    1785          30 :                         SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE)
    1786             :             {
    1787          30 :                 oField.SetSpatialRef(poSRS2);
    1788             :             }
    1789          30 :             poSRS2->Release();
    1790             :         }
    1791             :         else
    1792             :         {
    1793         608 :             oField.SetSpatialRef(poSRS);
    1794             :         }
    1795         638 :         oField.SetNullable(poProperty->IsNullable());
    1796         638 :         oField.SetCoordinatePrecision(poProperty->GetCoordinatePrecision());
    1797         638 :         poLayer->GetLayerDefn()->AddGeomFieldDefn(&oField);
    1798             :     }
    1799             : 
    1800         579 :     if (poReader->GetClassCount() == 1)
    1801             :     {
    1802         336 :         int iInsertPos = 0;
    1803         341 :         for (const auto &osElt : m_aosGMLExtraElements)
    1804             :         {
    1805             :             GMLPropertyDefn *poProperty =
    1806           5 :                 new GMLPropertyDefn(osElt.c_str(), osElt.c_str());
    1807           5 :             poProperty->SetType(GMLPT_String);
    1808           5 :             if (poClass->AddProperty(poProperty, iInsertPos) == iInsertPos)
    1809           3 :                 ++iInsertPos;
    1810             :             else
    1811           2 :                 delete poProperty;
    1812             :         }
    1813             :     }
    1814             : 
    1815        2775 :     for (int iField = 0; iField < poClass->GetPropertyCount(); iField++)
    1816             :     {
    1817        2196 :         GMLPropertyDefn *poProperty = poClass->GetProperty(iField);
    1818        2196 :         OGRFieldSubType eSubType = poProperty->GetSubType();
    1819             :         const OGRFieldType eFType =
    1820        2196 :             GML_GetOGRFieldType(poProperty->GetType(), eSubType);
    1821        4392 :         OGRFieldDefn oField(poProperty->GetName(), eFType);
    1822        2196 :         oField.SetSubType(eSubType);
    1823        2196 :         if (STARTS_WITH_CI(oField.GetNameRef(), "ogr:"))
    1824           0 :             oField.SetName(poProperty->GetName() + 4);
    1825        2196 :         if (poProperty->GetWidth() > 0)
    1826         662 :             oField.SetWidth(poProperty->GetWidth());
    1827        2196 :         if (poProperty->GetPrecision() > 0)
    1828          45 :             oField.SetPrecision(poProperty->GetPrecision());
    1829        2196 :         if (!bEmptyAsNull)
    1830           2 :             oField.SetNullable(poProperty->IsNullable());
    1831        2196 :         oField.SetUnique(poProperty->IsUnique());
    1832        2196 :         oField.SetComment(poProperty->GetDocumentation());
    1833        2196 :         poLayer->GetLayerDefn()->AddFieldDefn(&oField);
    1834             :     }
    1835             : 
    1836         579 :     if (poSRS != nullptr)
    1837         168 :         poSRS->Release();
    1838             : 
    1839         579 :     return poLayer;
    1840             : }
    1841             : 
    1842             : /************************************************************************/
    1843             : /*                         GetGlobalSRSName()                           */
    1844             : /************************************************************************/
    1845             : 
    1846        1090 : const char *OGRGMLDataSource::GetGlobalSRSName()
    1847             : {
    1848        1090 :     if (poReader->CanUseGlobalSRSName() || bUseGlobalSRSName)
    1849         507 :         return poReader->GetGlobalSRSName();
    1850             :     else
    1851         583 :         return nullptr;
    1852             : }
    1853             : 
    1854             : /************************************************************************/
    1855             : /*                               Create()                               */
    1856             : /************************************************************************/
    1857             : 
    1858         101 : bool OGRGMLDataSource::Create(const char *pszFilename, char **papszOptions)
    1859             : 
    1860             : {
    1861         101 :     if (fpOutput != nullptr || poReader != nullptr)
    1862             :     {
    1863           0 :         CPLAssert(false);
    1864             :         return false;
    1865             :     }
    1866             : 
    1867         101 :     if (strcmp(pszFilename, "/dev/stdout") == 0)
    1868           0 :         pszFilename = "/vsistdout/";
    1869             : 
    1870             :     // Read options.
    1871         101 :     CSLDestroy(papszCreateOptions);
    1872         101 :     papszCreateOptions = CSLDuplicate(papszOptions);
    1873             : 
    1874             :     const char *pszFormat =
    1875         101 :         CSLFetchNameValueDef(papszCreateOptions, "FORMAT", "GML3.2");
    1876         101 :     bIsOutputGML3 = EQUAL(pszFormat, "GML3");
    1877         101 :     bIsOutputGML3Deegree = EQUAL(pszFormat, "GML3Deegree");
    1878         101 :     bIsOutputGML32 = EQUAL(pszFormat, "GML3.2");
    1879         101 :     if (bIsOutputGML3Deegree || bIsOutputGML32)
    1880          79 :         bIsOutputGML3 = true;
    1881             : 
    1882         101 :     eSRSNameFormat = (bIsOutputGML3) ? SRSNAME_OGC_URN : SRSNAME_SHORT;
    1883         101 :     if (bIsOutputGML3)
    1884             :     {
    1885             :         const char *pszLongSRS =
    1886          91 :             CSLFetchNameValue(papszCreateOptions, "GML3_LONGSRS");
    1887             :         const char *pszSRSNameFormat =
    1888          91 :             CSLFetchNameValue(papszCreateOptions, "SRSNAME_FORMAT");
    1889          91 :         if (pszSRSNameFormat)
    1890             :         {
    1891           6 :             if (pszLongSRS)
    1892             :             {
    1893           0 :                 CPLError(CE_Warning, CPLE_NotSupported,
    1894             :                          "Both GML3_LONGSRS and SRSNAME_FORMAT specified. "
    1895             :                          "Ignoring GML3_LONGSRS");
    1896             :             }
    1897           6 :             if (EQUAL(pszSRSNameFormat, "SHORT"))
    1898           1 :                 eSRSNameFormat = SRSNAME_SHORT;
    1899           5 :             else if (EQUAL(pszSRSNameFormat, "OGC_URN"))
    1900           1 :                 eSRSNameFormat = SRSNAME_OGC_URN;
    1901           4 :             else if (EQUAL(pszSRSNameFormat, "OGC_URL"))
    1902           4 :                 eSRSNameFormat = SRSNAME_OGC_URL;
    1903             :             else
    1904             :             {
    1905           0 :                 CPLError(CE_Warning, CPLE_NotSupported,
    1906             :                          "Invalid value for SRSNAME_FORMAT. "
    1907             :                          "Using SRSNAME_OGC_URN");
    1908             :             }
    1909             :         }
    1910          85 :         else if (pszLongSRS && !CPLTestBool(pszLongSRS))
    1911           0 :             eSRSNameFormat = SRSNAME_SHORT;
    1912             :     }
    1913             : 
    1914         101 :     bWriteSpaceIndentation = CPLTestBool(
    1915         101 :         CSLFetchNameValueDef(papszCreateOptions, "SPACE_INDENTATION", "YES"));
    1916             : 
    1917             :     // Create the output file.
    1918         101 :     osFilename = pszFilename;
    1919         101 :     SetDescription(pszFilename);
    1920             : 
    1921         101 :     if (strcmp(pszFilename, "/vsistdout/") == 0 ||
    1922         101 :         STARTS_WITH(pszFilename, "/vsigzip/"))
    1923             :     {
    1924           0 :         fpOutput = VSIFOpenExL(pszFilename, "wb", true);
    1925           0 :         bFpOutputIsNonSeekable = true;
    1926           0 :         bFpOutputSingleFile = true;
    1927             :     }
    1928         101 :     else if (STARTS_WITH(pszFilename, "/vsizip/"))
    1929             :     {
    1930           0 :         if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "zip"))
    1931             :         {
    1932           0 :             SetDescription(
    1933           0 :                 CPLFormFilenameSafe(pszFilename, "out.gml", nullptr).c_str());
    1934             :         }
    1935             : 
    1936           0 :         fpOutput = VSIFOpenExL(GetDescription(), "wb", true);
    1937           0 :         bFpOutputIsNonSeekable = true;
    1938             :     }
    1939             :     else
    1940         101 :         fpOutput = VSIFOpenExL(pszFilename, "wb+", true);
    1941         101 :     if (fpOutput == nullptr)
    1942             :     {
    1943           1 :         CPLError(CE_Failure, CPLE_OpenFailed,
    1944             :                  "Failed to create GML file %s: %s", pszFilename,
    1945             :                  VSIGetLastErrorMsg());
    1946           1 :         return false;
    1947             :     }
    1948             : 
    1949             :     // Write out "standard" header.
    1950         100 :     PrintLine(fpOutput, "%s", "<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    1951             : 
    1952         100 :     if (!bFpOutputIsNonSeekable)
    1953         100 :         nSchemaInsertLocation = static_cast<int>(VSIFTellL(fpOutput));
    1954             : 
    1955         100 :     const char *pszPrefix = GetAppPrefix();
    1956         100 :     const char *pszTargetNameSpace = CSLFetchNameValueDef(
    1957             :         papszOptions, "TARGET_NAMESPACE", "http://ogr.maptools.org/");
    1958             : 
    1959         100 :     if (GMLFeatureCollection())
    1960           1 :         PrintLine(fpOutput, "<gml:FeatureCollection");
    1961          99 :     else if (RemoveAppPrefix())
    1962           2 :         PrintLine(fpOutput, "<FeatureCollection");
    1963             :     else
    1964          97 :         PrintLine(fpOutput, "<%s:FeatureCollection", pszPrefix);
    1965             : 
    1966         100 :     if (IsGML32Output())
    1967             :     {
    1968          77 :         char *pszGMLId = CPLEscapeString(
    1969             :             CSLFetchNameValueDef(papszOptions, "GML_ID", "aFeatureCollection"),
    1970             :             -1, CPLES_XML);
    1971          77 :         PrintLine(fpOutput, "     gml:id=\"%s\"", pszGMLId);
    1972          77 :         CPLFree(pszGMLId);
    1973             :     }
    1974             : 
    1975             :     // Write out schema info if provided in creation options.
    1976         100 :     const char *pszSchemaURI = CSLFetchNameValue(papszOptions, "XSISCHEMAURI");
    1977         100 :     const char *pszSchemaOpt = CSLFetchNameValue(papszOptions, "XSISCHEMA");
    1978             : 
    1979         100 :     if (pszSchemaURI != nullptr)
    1980             :     {
    1981           0 :         PrintLine(
    1982             :             fpOutput,
    1983             :             "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    1984           0 :         PrintLine(fpOutput, "     xsi:schemaLocation=\"%s\"", pszSchemaURI);
    1985             :     }
    1986         100 :     else if (pszSchemaOpt == nullptr || EQUAL(pszSchemaOpt, "EXTERNAL"))
    1987             :     {
    1988             :         char *pszBasename =
    1989          98 :             CPLStrdup(CPLGetBasenameSafe(GetDescription()).c_str());
    1990             : 
    1991          98 :         PrintLine(
    1992             :             fpOutput,
    1993             :             "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    1994          98 :         PrintLine(fpOutput, "     xsi:schemaLocation=\"%s %s\"",
    1995             :                   pszTargetNameSpace,
    1996         196 :                   CPLResetExtensionSafe(pszBasename, "xsd").c_str());
    1997          98 :         CPLFree(pszBasename);
    1998             :     }
    1999             : 
    2000         100 :     if (RemoveAppPrefix())
    2001           2 :         PrintLine(fpOutput, "     xmlns=\"%s\"", pszTargetNameSpace);
    2002             :     else
    2003          98 :         PrintLine(fpOutput, "     xmlns:%s=\"%s\"", pszPrefix,
    2004             :                   pszTargetNameSpace);
    2005             : 
    2006         100 :     if (IsGML32Output())
    2007          77 :         PrintLine(fpOutput, "%s",
    2008             :                   "     xmlns:gml=\"http://www.opengis.net/gml/3.2\">");
    2009             :     else
    2010          23 :         PrintLine(fpOutput, "%s",
    2011             :                   "     xmlns:gml=\"http://www.opengis.net/gml\">");
    2012             : 
    2013         100 :     return true;
    2014             : }
    2015             : 
    2016             : /************************************************************************/
    2017             : /*                         WriteTopElements()                           */
    2018             : /************************************************************************/
    2019             : 
    2020         100 : void OGRGMLDataSource::WriteTopElements()
    2021             : {
    2022         300 :     const char *pszDescription = CSLFetchNameValueDef(
    2023         100 :         papszCreateOptions, "DESCRIPTION", GetMetadataItem("DESCRIPTION"));
    2024         100 :     if (pszDescription != nullptr)
    2025             :     {
    2026           2 :         if (bWriteSpaceIndentation)
    2027           2 :             VSIFPrintfL(fpOutput, "  ");
    2028           2 :         char *pszTmp = CPLEscapeString(pszDescription, -1, CPLES_XML);
    2029           2 :         PrintLine(fpOutput, "<gml:description>%s</gml:description>", pszTmp);
    2030           2 :         CPLFree(pszTmp);
    2031             :     }
    2032             : 
    2033         100 :     const char *l_pszName = CSLFetchNameValueDef(papszCreateOptions, "NAME",
    2034         100 :                                                  GetMetadataItem("NAME"));
    2035         100 :     if (l_pszName != nullptr)
    2036             :     {
    2037           2 :         if (bWriteSpaceIndentation)
    2038           2 :             VSIFPrintfL(fpOutput, "  ");
    2039           2 :         char *pszTmp = CPLEscapeString(l_pszName, -1, CPLES_XML);
    2040           2 :         PrintLine(fpOutput, "<gml:name>%s</gml:name>", pszTmp);
    2041           2 :         CPLFree(pszTmp);
    2042             :     }
    2043             : 
    2044             :     // Should we initialize an area to place the boundedBy element?
    2045             :     // We will need to seek back to fill it in.
    2046         100 :     nBoundedByLocation = -1;
    2047         100 :     if (CPLFetchBool(papszCreateOptions, "BOUNDEDBY", true))
    2048             :     {
    2049         100 :         if (!bFpOutputIsNonSeekable)
    2050             :         {
    2051         100 :             nBoundedByLocation = static_cast<int>(VSIFTellL(fpOutput));
    2052             : 
    2053         100 :             if (nBoundedByLocation != -1)
    2054         100 :                 PrintLine(fpOutput, "%350s", "");
    2055             :         }
    2056             :         else
    2057             :         {
    2058           0 :             if (bWriteSpaceIndentation)
    2059           0 :                 VSIFPrintfL(fpOutput, "  ");
    2060           0 :             if (IsGML3Output())
    2061           0 :                 PrintLine(fpOutput,
    2062             :                           "<gml:boundedBy><gml:Null /></gml:boundedBy>");
    2063             :             else
    2064           0 :                 PrintLine(fpOutput, "<gml:boundedBy><gml:null>missing</"
    2065             :                                     "gml:null></gml:boundedBy>");
    2066             :         }
    2067             :     }
    2068         100 : }
    2069             : 
    2070             : /************************************************************************/
    2071             : /*                 DealWithOgrSchemaOpenOption()                        */
    2072             : /************************************************************************/
    2073             : 
    2074         446 : bool OGRGMLDataSource::DealWithOgrSchemaOpenOption(
    2075             :     const GDALOpenInfo *poOpenInfo)
    2076             : {
    2077             : 
    2078             :     std::string osFieldsSchemaOverrideParam =
    2079         892 :         CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "OGR_SCHEMA", "");
    2080             : 
    2081         446 :     if (!osFieldsSchemaOverrideParam.empty())
    2082             :     {
    2083             : 
    2084             :         // GML driver does not support update at the moment so this will never happen
    2085          26 :         if (poOpenInfo->eAccess == GA_Update)
    2086             :         {
    2087           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2088             :                      "OGR_SCHEMA open option is not supported in update mode.");
    2089          10 :             return false;
    2090             :         }
    2091             : 
    2092          26 :         OGRSchemaOverride osSchemaOverride;
    2093          50 :         if (!osSchemaOverride.LoadFromJSON(osFieldsSchemaOverrideParam) ||
    2094          24 :             !osSchemaOverride.IsValid())
    2095             :         {
    2096           2 :             return false;
    2097             :         }
    2098             : 
    2099          24 :         const auto &oLayerOverrides = osSchemaOverride.GetLayerOverrides();
    2100          42 :         for (const auto &oLayer : oLayerOverrides)
    2101             :         {
    2102          26 :             const auto &oLayerName = oLayer.first;
    2103          26 :             const auto &oLayerFieldOverride = oLayer.second;
    2104          26 :             const bool bIsFullOverride{oLayerFieldOverride.IsFullOverride()};
    2105          26 :             std::vector<GMLPropertyDefn *> aoProperties;
    2106             : 
    2107          26 :             CPLDebug("GML", "Applying schema override for layer %s",
    2108             :                      oLayerName.c_str());
    2109             : 
    2110             :             // Fail if the layer name does not exist
    2111          26 :             const auto oClass = poReader->GetClass(oLayerName.c_str());
    2112          26 :             if (oClass == nullptr)
    2113             :             {
    2114           6 :                 CPLError(CE_Failure, CPLE_AppDefined, "Layer %s not found",
    2115             :                          oLayerName.c_str());
    2116           6 :                 return false;
    2117             :             }
    2118             : 
    2119          20 :             const auto &oLayerFields = oLayerFieldOverride.GetFieldOverrides();
    2120          42 :             for (const auto &oFieldOverrideIt : oLayerFields)
    2121             :             {
    2122             :                 const auto oProperty =
    2123          24 :                     oClass->GetProperty(oFieldOverrideIt.first.c_str());
    2124          24 :                 if (oProperty == nullptr)
    2125             :                 {
    2126           2 :                     CPLError(CE_Failure, CPLE_AppDefined,
    2127             :                              "Field %s not found in layer %s",
    2128             :                              oFieldOverrideIt.first.c_str(),
    2129             :                              oLayerName.c_str());
    2130           2 :                     return false;
    2131             :                 }
    2132             : 
    2133          22 :                 const auto &oFieldOverride = oFieldOverrideIt.second;
    2134             : 
    2135             :                 const OGRFieldSubType eSubType =
    2136          22 :                     oFieldOverride.GetFieldSubType().value_or(OFSTNone);
    2137             : 
    2138          22 :                 if (oFieldOverride.GetFieldSubType().has_value())
    2139             :                 {
    2140           8 :                     oProperty->SetSubType(eSubType);
    2141             :                 }
    2142             : 
    2143          22 :                 if (oFieldOverride.GetFieldType().has_value())
    2144             :                 {
    2145          12 :                     oProperty->SetType(GML_FromOGRFieldType(
    2146          24 :                         oFieldOverride.GetFieldType().value(), eSubType));
    2147             :                 }
    2148             : 
    2149          22 :                 if (oFieldOverride.GetFieldName().has_value())
    2150             :                 {
    2151           4 :                     oProperty->SetName(
    2152           8 :                         oFieldOverride.GetFieldName().value().c_str());
    2153             :                 }
    2154             : 
    2155          22 :                 if (oFieldOverride.GetFieldWidth().has_value())
    2156             :                 {
    2157           2 :                     oProperty->SetWidth(oFieldOverride.GetFieldWidth().value());
    2158             :                 }
    2159             : 
    2160          22 :                 if (oFieldOverride.GetFieldPrecision().has_value())
    2161             :                 {
    2162           4 :                     oProperty->SetPrecision(
    2163           2 :                         oFieldOverride.GetFieldPrecision().value());
    2164             :                 }
    2165             : 
    2166          22 :                 if (bIsFullOverride)
    2167             :                 {
    2168           4 :                     aoProperties.push_back(oProperty);
    2169             :                 }
    2170             :             }
    2171             : 
    2172             :             // Remove fields not in the override
    2173          20 :             if (bIsFullOverride &&
    2174           2 :                 aoProperties.size() !=
    2175           2 :                     static_cast<size_t>(oClass->GetPropertyCount()))
    2176             :             {
    2177           8 :                 for (int j = 0; j < oClass->GetPropertyCount(); ++j)
    2178             :                 {
    2179           6 :                     const auto oProperty = oClass->GetProperty(j);
    2180           6 :                     if (std::find(aoProperties.begin(), aoProperties.end(),
    2181           6 :                                   oProperty) == aoProperties.end())
    2182             :                     {
    2183           2 :                         delete (oProperty);
    2184             :                     }
    2185             :                 }
    2186             : 
    2187           2 :                 oClass->StealProperties();
    2188             : 
    2189           6 :                 for (const auto &oProperty : aoProperties)
    2190             :                 {
    2191           4 :                     oClass->AddProperty(oProperty);
    2192             :                 }
    2193             :             }
    2194             :         }
    2195             :     }
    2196         436 :     return true;
    2197             : }
    2198             : 
    2199             : /************************************************************************/
    2200             : /*                         DeclareNewWriteSRS()                         */
    2201             : /************************************************************************/
    2202             : 
    2203             : // Check that all SRS passed to ICreateLayer() and CreateGeomField()
    2204             : // are the same (or all null)
    2205             : 
    2206         124 : void OGRGMLDataSource::DeclareNewWriteSRS(const OGRSpatialReference *poSRS)
    2207             : {
    2208         124 :     if (m_bWriteGlobalSRS)
    2209             :     {
    2210         124 :         if (!m_bWriteGlobalSRSInit)
    2211             :         {
    2212          91 :             m_bWriteGlobalSRSInit = true;
    2213          91 :             if (poSRS)
    2214             :             {
    2215          27 :                 m_poWriteGlobalSRS.reset(poSRS->Clone());
    2216          27 :                 m_poWriteGlobalSRS->SetAxisMappingStrategy(
    2217             :                     OAMS_TRADITIONAL_GIS_ORDER);
    2218             :             }
    2219             :         }
    2220             :         else
    2221             :         {
    2222          33 :             if (m_poWriteGlobalSRS)
    2223             :             {
    2224           3 :                 const char *const apszOptions[] = {
    2225             :                     "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
    2226           5 :                 if (!poSRS ||
    2227           2 :                     !poSRS->IsSame(m_poWriteGlobalSRS.get(), apszOptions))
    2228             :                 {
    2229           2 :                     m_bWriteGlobalSRS = false;
    2230             :                 }
    2231             :             }
    2232             :             else
    2233             :             {
    2234          30 :                 if (poSRS)
    2235           1 :                     m_bWriteGlobalSRS = false;
    2236             :             }
    2237             :         }
    2238             :     }
    2239         124 : }
    2240             : 
    2241             : /************************************************************************/
    2242             : /*                           ICreateLayer()                             */
    2243             : /************************************************************************/
    2244             : 
    2245             : OGRLayer *
    2246         126 : OGRGMLDataSource::ICreateLayer(const char *pszLayerName,
    2247             :                                const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    2248             :                                CSLConstList /*papszOptions*/)
    2249             : {
    2250             :     // Verify we are in update mode.
    2251         126 :     if (fpOutput == nullptr)
    2252             :     {
    2253           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    2254             :                  "Data source %s opened for read access.\n"
    2255             :                  "New layer %s cannot be created.\n",
    2256           0 :                  GetDescription(), pszLayerName);
    2257             : 
    2258           0 :         return nullptr;
    2259             :     }
    2260             : 
    2261             :     const auto eType =
    2262         126 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    2263             :     const auto poSRS =
    2264         126 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    2265             : 
    2266             :     // Ensure name is safe as an element name.
    2267         126 :     char *pszCleanLayerName = CPLStrdup(pszLayerName);
    2268             : 
    2269         126 :     CPLCleanXMLElementName(pszCleanLayerName);
    2270         126 :     if (strcmp(pszCleanLayerName, pszLayerName) != 0)
    2271             :     {
    2272           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    2273             :                  "Layer name '%s' adjusted to '%s' for XML validity.",
    2274             :                  pszLayerName, pszCleanLayerName);
    2275             :     }
    2276             : 
    2277         126 :     if (nLayers == 0)
    2278             :     {
    2279          97 :         WriteTopElements();
    2280             :     }
    2281             : 
    2282             :     // Create the layer object.
    2283         126 :     OGRLayer *poLayer = new OGRGMLLayer(pszCleanLayerName, true, this);
    2284         126 :     OGRFeatureDefn *poLayerDefn = poLayer->GetLayerDefn();
    2285         126 :     poLayerDefn->SetGeomType(eType);
    2286         126 :     if (eType != wkbNone)
    2287             :     {
    2288         105 :         auto poGeomFieldDefn = poLayerDefn->GetGeomFieldDefn(0);
    2289         105 :         const char *pszGeomFieldName = poSrcGeomFieldDefn->GetNameRef();
    2290         105 :         if (!pszGeomFieldName || pszGeomFieldName[0] == 0)
    2291         104 :             pszGeomFieldName = "geometryProperty";
    2292         105 :         poGeomFieldDefn->SetName(pszGeomFieldName);
    2293         105 :         poGeomFieldDefn->SetNullable(poSrcGeomFieldDefn->IsNullable());
    2294         105 :         DeclareNewWriteSRS(poSRS);
    2295         105 :         if (poSRS != nullptr)
    2296             :         {
    2297          24 :             auto poSRSClone = poSRS->Clone();
    2298          24 :             poSRSClone->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2299          24 :             poGeomFieldDefn->SetSpatialRef(poSRSClone);
    2300          24 :             poSRSClone->Dereference();
    2301             :         }
    2302         105 :         poGeomFieldDefn->SetCoordinatePrecision(
    2303             :             poSrcGeomFieldDefn->GetCoordinatePrecision());
    2304             :     }
    2305             : 
    2306         126 :     CPLFree(pszCleanLayerName);
    2307             : 
    2308             :     // Add layer to data source layer list.
    2309         126 :     papoLayers = static_cast<OGRLayer **>(
    2310         126 :         CPLRealloc(papoLayers, sizeof(OGRLayer *) * (nLayers + 1)));
    2311             : 
    2312         126 :     papoLayers[nLayers++] = poLayer;
    2313             : 
    2314         126 :     return poLayer;
    2315             : }
    2316             : 
    2317             : /************************************************************************/
    2318             : /*                           TestCapability()                           */
    2319             : /************************************************************************/
    2320             : 
    2321         172 : int OGRGMLDataSource::TestCapability(const char *pszCap) const
    2322             : 
    2323             : {
    2324         172 :     if (EQUAL(pszCap, ODsCCreateLayer))
    2325          68 :         return TRUE;
    2326         104 :     else if (EQUAL(pszCap, ODsCCreateGeomFieldAfterCreateLayer))
    2327          42 :         return TRUE;
    2328          62 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    2329           5 :         return bIsOutputGML3;
    2330          57 :     else if (EQUAL(pszCap, ODsCZGeometries))
    2331           2 :         return TRUE;
    2332          55 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite))
    2333           0 :         return TRUE;
    2334             :     else
    2335          55 :         return FALSE;
    2336             : }
    2337             : 
    2338             : /************************************************************************/
    2339             : /*                              GetLayer()                              */
    2340             : /************************************************************************/
    2341             : 
    2342         889 : const OGRLayer *OGRGMLDataSource::GetLayer(int iLayer) const
    2343             : 
    2344             : {
    2345         889 :     if (iLayer < 0 || iLayer >= nLayers)
    2346           7 :         return nullptr;
    2347             :     else
    2348         882 :         return papoLayers[iLayer];
    2349             : }
    2350             : 
    2351             : /************************************************************************/
    2352             : /*                            GrowExtents()                             */
    2353             : /************************************************************************/
    2354             : 
    2355         211 : void OGRGMLDataSource::GrowExtents(OGREnvelope3D *psGeomBounds,
    2356             :                                    int nCoordDimension)
    2357             : 
    2358             : {
    2359         211 :     sBoundingRect.Merge(*psGeomBounds);
    2360         211 :     if (nCoordDimension == 3)
    2361          46 :         bBBOX3D = true;
    2362         211 : }
    2363             : 
    2364             : /************************************************************************/
    2365             : /*                            InsertHeader()                            */
    2366             : /*                                                                      */
    2367             : /*      This method is used to update boundedby info for a              */
    2368             : /*      dataset, and insert schema descriptions depending on            */
    2369             : /*      selection options in effect.                                    */
    2370             : /************************************************************************/
    2371             : 
    2372          99 : void OGRGMLDataSource::InsertHeader()
    2373             : 
    2374             : {
    2375          99 :     int nSchemaStart = 0;
    2376             : 
    2377          99 :     if (bFpOutputSingleFile)
    2378           0 :         return;
    2379             : 
    2380             :     // Do we want to write the schema within the GML instance doc
    2381             :     // or to a separate file?  For now we only support external.
    2382             :     const char *pszSchemaURI =
    2383          99 :         CSLFetchNameValue(papszCreateOptions, "XSISCHEMAURI");
    2384             :     const char *pszSchemaOpt =
    2385          99 :         CSLFetchNameValue(papszCreateOptions, "XSISCHEMA");
    2386             : 
    2387          99 :     const bool bGMLFeatureCollection = GMLFeatureCollection();
    2388             : 
    2389          99 :     if (pszSchemaURI != nullptr)
    2390           0 :         return;
    2391             : 
    2392          99 :     VSILFILE *fpSchema = nullptr;
    2393          99 :     if (pszSchemaOpt == nullptr || EQUAL(pszSchemaOpt, "EXTERNAL"))
    2394             :     {
    2395             :         const std::string l_osXSDFilename =
    2396          98 :             CPLResetExtensionSafe(GetDescription(), "xsd");
    2397             : 
    2398          98 :         fpSchema = VSIFOpenL(l_osXSDFilename.c_str(), "wt");
    2399          98 :         if (fpSchema == nullptr)
    2400             :         {
    2401           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    2402             :                      "Failed to open file %.500s for schema output.",
    2403             :                      l_osXSDFilename.c_str());
    2404           0 :             return;
    2405             :         }
    2406         196 :         PrintLine(fpSchema, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    2407             :     }
    2408           1 :     else if (EQUAL(pszSchemaOpt, "INTERNAL"))
    2409             :     {
    2410           0 :         if (fpOutput == nullptr)
    2411           0 :             return;
    2412           0 :         nSchemaStart = static_cast<int>(VSIFTellL(fpOutput));
    2413           0 :         fpSchema = fpOutput;
    2414             :     }
    2415             :     else
    2416             :     {
    2417           1 :         return;
    2418             :     }
    2419             : 
    2420             :     // Write the schema section at the end of the file.  Once
    2421             :     // complete, we will read it back in, and then move the whole
    2422             :     // file "down" enough to insert the schema at the beginning.
    2423             : 
    2424             :     // Detect if there are fields of List types.
    2425          98 :     bool bHasListFields = false;
    2426             : 
    2427          98 :     const int nLayerCount = OGRGMLDataSource::GetLayerCount();
    2428         223 :     for (int iLayer = 0; !bHasListFields && iLayer < nLayerCount; iLayer++)
    2429             :     {
    2430         125 :         OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
    2431         294 :         for (int iField = 0;
    2432         294 :              !bHasListFields && iField < poFDefn->GetFieldCount(); iField++)
    2433             :         {
    2434         169 :             OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
    2435             : 
    2436         336 :             if (poFieldDefn->GetType() == OFTIntegerList ||
    2437         334 :                 poFieldDefn->GetType() == OFTInteger64List ||
    2438         503 :                 poFieldDefn->GetType() == OFTRealList ||
    2439         167 :                 poFieldDefn->GetType() == OFTStringList)
    2440             :             {
    2441           3 :                 bHasListFields = true;
    2442             :             }
    2443             :         }
    2444             :     }
    2445             : 
    2446             :     // Emit the start of the schema section.
    2447          98 :     const char *pszPrefix = GetAppPrefix();
    2448          98 :     if (pszPrefix[0] == '\0')
    2449           0 :         pszPrefix = "ogr";
    2450         196 :     const char *pszTargetNameSpace = CSLFetchNameValueDef(
    2451          98 :         papszCreateOptions, "TARGET_NAMESPACE", "http://ogr.maptools.org/");
    2452             : 
    2453          98 :     if (IsGML3Output())
    2454             :     {
    2455          88 :         PrintLine(fpSchema, "<xs:schema ");
    2456          88 :         PrintLine(fpSchema, "    targetNamespace=\"%s\"", pszTargetNameSpace);
    2457          88 :         PrintLine(fpSchema, "    xmlns:%s=\"%s\"", pszPrefix,
    2458             :                   pszTargetNameSpace);
    2459          88 :         PrintLine(fpSchema,
    2460             :                   "    xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"");
    2461          88 :         if (IsGML32Output())
    2462             :         {
    2463          75 :             PrintLine(fpSchema,
    2464             :                       "    xmlns:gml=\"http://www.opengis.net/gml/3.2\"");
    2465          75 :             if (!bGMLFeatureCollection)
    2466             :             {
    2467          75 :                 PrintLine(
    2468             :                     fpSchema,
    2469             :                     "    xmlns:gmlsf=\"http://www.opengis.net/gmlsf/2.0\"");
    2470             :             }
    2471             :         }
    2472             :         else
    2473             :         {
    2474          13 :             PrintLine(fpSchema, "    xmlns:gml=\"http://www.opengis.net/gml\"");
    2475          13 :             if (!IsGML3DeegreeOutput() && !bGMLFeatureCollection)
    2476             :             {
    2477          11 :                 PrintLine(fpSchema,
    2478             :                           "    xmlns:gmlsf=\"http://www.opengis.net/gmlsf\"");
    2479             :             }
    2480             :         }
    2481          88 :         PrintLine(fpSchema, "    elementFormDefault=\"qualified\"");
    2482          88 :         PrintLine(fpSchema, "    version=\"1.0\">");
    2483             : 
    2484          88 :         if (IsGML32Output())
    2485             :         {
    2486          75 :             if (!bGMLFeatureCollection)
    2487             :             {
    2488          75 :                 PrintLine(fpSchema, "<xs:annotation>");
    2489          75 :                 PrintLine(fpSchema, "  <xs:appinfo "
    2490             :                                     "source=\"http://schemas.opengis.net/"
    2491             :                                     "gmlsfProfile/2.0/gmlsfLevels.xsd\">");
    2492          75 :                 PrintLine(
    2493             :                     fpSchema,
    2494             :                     "    <gmlsf:ComplianceLevel>%d</gmlsf:ComplianceLevel>",
    2495             :                     (bHasListFields) ? 1 : 0);
    2496          75 :                 PrintLine(fpSchema, "  </xs:appinfo>");
    2497          75 :                 PrintLine(fpSchema, "</xs:annotation>");
    2498             :             }
    2499             : 
    2500          75 :             PrintLine(fpSchema,
    2501             :                       "<xs:import namespace=\"http://www.opengis.net/gml/3.2\" "
    2502             :                       "schemaLocation=\"http://schemas.opengis.net/gml/3.2.1/"
    2503             :                       "gml.xsd\"/>");
    2504          75 :             if (!bGMLFeatureCollection)
    2505             :             {
    2506          75 :                 PrintLine(
    2507             :                     fpSchema,
    2508             :                     "<xs:import namespace=\"http://www.opengis.net/gmlsf/2.0\" "
    2509             :                     "schemaLocation=\"http://schemas.opengis.net/gmlsfProfile/"
    2510             :                     "2.0/gmlsfLevels.xsd\"/>");
    2511             :             }
    2512             :         }
    2513             :         else
    2514             :         {
    2515          13 :             if (!IsGML3DeegreeOutput() && !bGMLFeatureCollection)
    2516             :             {
    2517          11 :                 PrintLine(fpSchema, "<xs:annotation>");
    2518          11 :                 PrintLine(fpSchema,
    2519             :                           "  <xs:appinfo "
    2520             :                           "source=\"http://schemas.opengis.net/gml/3.1.1/"
    2521             :                           "profiles/gmlsfProfile/1.0.0/gmlsfLevels.xsd\">");
    2522          11 :                 PrintLine(
    2523             :                     fpSchema,
    2524             :                     "    <gmlsf:ComplianceLevel>%d</gmlsf:ComplianceLevel>",
    2525             :                     (bHasListFields) ? 1 : 0);
    2526          11 :                 PrintLine(fpSchema,
    2527             :                           "    "
    2528             :                           "<gmlsf:GMLProfileSchema>http://schemas.opengis.net/"
    2529             :                           "gml/3.1.1/profiles/gmlsfProfile/1.0.0/gmlsf.xsd</"
    2530             :                           "gmlsf:GMLProfileSchema>");
    2531          11 :                 PrintLine(fpSchema, "  </xs:appinfo>");
    2532          11 :                 PrintLine(fpSchema, "</xs:annotation>");
    2533             :             }
    2534             : 
    2535          13 :             PrintLine(fpSchema,
    2536             :                       "<xs:import namespace=\"http://www.opengis.net/gml\" "
    2537             :                       "schemaLocation=\"http://schemas.opengis.net/gml/3.1.1/"
    2538             :                       "base/gml.xsd\"/>");
    2539          13 :             if (!IsGML3DeegreeOutput() && !bGMLFeatureCollection)
    2540             :             {
    2541          11 :                 PrintLine(
    2542             :                     fpSchema,
    2543             :                     "<xs:import namespace=\"http://www.opengis.net/gmlsf\" "
    2544             :                     "schemaLocation=\"http://schemas.opengis.net/gml/3.1.1/"
    2545             :                     "profiles/gmlsfProfile/1.0.0/gmlsfLevels.xsd\"/>");
    2546             :             }
    2547             :         }
    2548             :     }
    2549             :     else
    2550             :     {
    2551          10 :         PrintLine(fpSchema,
    2552             :                   "<xs:schema targetNamespace=\"%s\" xmlns:%s=\"%s\" "
    2553             :                   "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" "
    2554             :                   "xmlns:gml=\"http://www.opengis.net/gml\" "
    2555             :                   "elementFormDefault=\"qualified\" version=\"1.0\">",
    2556             :                   pszTargetNameSpace, pszPrefix, pszTargetNameSpace);
    2557             : 
    2558          10 :         PrintLine(fpSchema,
    2559             :                   "<xs:import namespace=\"http://www.opengis.net/gml\" "
    2560             :                   "schemaLocation=\"http://schemas.opengis.net/gml/2.1.2/"
    2561             :                   "feature.xsd\"/>");
    2562             :     }
    2563             : 
    2564             :     // Define the FeatureCollection element
    2565          98 :     if (!bGMLFeatureCollection)
    2566             :     {
    2567          97 :         bool bHasUniqueConstraints = false;
    2568         221 :         for (int iLayer = 0; (iLayer < nLayerCount) && !bHasUniqueConstraints;
    2569             :              iLayer++)
    2570             :         {
    2571         124 :             OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
    2572         124 :             const int nFieldCount = poFDefn->GetFieldCount();
    2573         302 :             for (int iField = 0;
    2574         302 :                  (iField < nFieldCount) && !bHasUniqueConstraints; iField++)
    2575             :             {
    2576         178 :                 const OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
    2577         178 :                 if (poFieldDefn->IsUnique())
    2578           0 :                     bHasUniqueConstraints = true;
    2579             :             }
    2580             :         }
    2581             : 
    2582          97 :         const char *pszFeatureMemberPrefix = pszPrefix;
    2583          97 :         if (IsGML3Output())
    2584             :         {
    2585          87 :             if (IsGML32Output())
    2586             :             {
    2587             :                 // GML Simple Features profile v2.0 mentions gml:AbstractGML as
    2588             :                 // substitutionGroup but using gml:AbstractFeature makes it
    2589             :                 // usablable by GMLJP2 v2.
    2590          75 :                 PrintLine(fpSchema,
    2591             :                           "<xs:element name=\"FeatureCollection\" "
    2592             :                           "type=\"%s:FeatureCollectionType\" "
    2593             :                           "substitutionGroup=\"gml:AbstractFeature\"%s>",
    2594             :                           pszPrefix, bHasUniqueConstraints ? "" : "/");
    2595             :             }
    2596          12 :             else if (IsGML3DeegreeOutput())
    2597             :             {
    2598           1 :                 PrintLine(fpSchema,
    2599             :                           "<xs:element name=\"FeatureCollection\" "
    2600             :                           "type=\"%s:FeatureCollectionType\" "
    2601             :                           "substitutionGroup=\"gml:_FeatureCollection\"%s>",
    2602             :                           pszPrefix, bHasUniqueConstraints ? "" : "/");
    2603             :             }
    2604             :             else
    2605             :             {
    2606          11 :                 PrintLine(fpSchema,
    2607             :                           "<xs:element name=\"FeatureCollection\" "
    2608             :                           "type=\"%s:FeatureCollectionType\" "
    2609             :                           "substitutionGroup=\"gml:_GML\"%s>",
    2610             :                           pszPrefix, bHasUniqueConstraints ? "" : "/");
    2611             :             }
    2612             :         }
    2613             :         else
    2614             :         {
    2615          10 :             pszFeatureMemberPrefix = "gml";
    2616          10 :             PrintLine(fpSchema,
    2617             :                       "<xs:element name=\"FeatureCollection\" "
    2618             :                       "type=\"%s:FeatureCollectionType\" "
    2619             :                       "substitutionGroup=\"gml:_FeatureCollection\"%s>",
    2620             :                       pszPrefix, bHasUniqueConstraints ? "" : "/");
    2621             :         }
    2622             : 
    2623          97 :         if (bHasUniqueConstraints)
    2624             :         {
    2625           0 :             for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
    2626             :             {
    2627           0 :                 OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
    2628           0 :                 const int nFieldCount = poFDefn->GetFieldCount();
    2629           0 :                 for (int iField = 0; iField < nFieldCount; iField++)
    2630             :                 {
    2631             :                     const OGRFieldDefn *poFieldDefn =
    2632           0 :                         poFDefn->GetFieldDefn(iField);
    2633           0 :                     if (poFieldDefn->IsUnique())
    2634             :                     {
    2635           0 :                         PrintLine(
    2636             :                             fpSchema,
    2637             :                             "  <xs:unique name=\"uniqueConstraint_%s_%s\">",
    2638           0 :                             poFDefn->GetName(), poFieldDefn->GetNameRef());
    2639           0 :                         PrintLine(fpSchema,
    2640             :                                   "    <xs:selector "
    2641             :                                   "xpath=\"%s:featureMember/%s:%s\"/>",
    2642             :                                   pszFeatureMemberPrefix, pszPrefix,
    2643           0 :                                   poFDefn->GetName());
    2644           0 :                         PrintLine(fpSchema, "    <xs:field xpath=\"%s:%s\"/>",
    2645             :                                   pszPrefix, poFieldDefn->GetNameRef());
    2646           0 :                         PrintLine(fpSchema, "  </xs:unique>");
    2647             :                     }
    2648             :                 }
    2649             :             }
    2650           0 :             PrintLine(fpSchema, "</xs:element>");
    2651             :         }
    2652             :     }
    2653             : 
    2654             :     // Define the FeatureCollectionType
    2655          98 :     if (IsGML3Output() && !bGMLFeatureCollection)
    2656             :     {
    2657          87 :         PrintLine(fpSchema, "<xs:complexType name=\"FeatureCollectionType\">");
    2658          87 :         PrintLine(fpSchema, "  <xs:complexContent>");
    2659          87 :         if (IsGML3DeegreeOutput())
    2660             :         {
    2661           1 :             PrintLine(fpSchema, "    <xs:extension "
    2662             :                                 "base=\"gml:AbstractFeatureCollectionType\">");
    2663           1 :             PrintLine(fpSchema, "      <xs:sequence>");
    2664           1 :             PrintLine(fpSchema, "        <xs:element name=\"featureMember\" "
    2665             :                                 "minOccurs=\"0\" maxOccurs=\"unbounded\">");
    2666             :         }
    2667             :         else
    2668             :         {
    2669          86 :             PrintLine(fpSchema,
    2670             :                       "    <xs:extension base=\"gml:AbstractFeatureType\">");
    2671          86 :             PrintLine(
    2672             :                 fpSchema,
    2673             :                 "      <xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">");
    2674          86 :             PrintLine(fpSchema, "        <xs:element name=\"featureMember\">");
    2675             :         }
    2676          87 :         PrintLine(fpSchema, "          <xs:complexType>");
    2677          87 :         if (IsGML32Output())
    2678             :         {
    2679          75 :             PrintLine(fpSchema, "            <xs:complexContent>");
    2680          75 :             PrintLine(fpSchema, "              <xs:extension "
    2681             :                                 "base=\"gml:AbstractFeatureMemberType\">");
    2682          75 :             PrintLine(fpSchema, "                <xs:sequence>");
    2683          75 :             PrintLine(
    2684             :                 fpSchema,
    2685             :                 "                  <xs:element ref=\"gml:AbstractFeature\"/>");
    2686          75 :             PrintLine(fpSchema, "                </xs:sequence>");
    2687          75 :             PrintLine(fpSchema, "              </xs:extension>");
    2688          75 :             PrintLine(fpSchema, "            </xs:complexContent>");
    2689             :         }
    2690             :         else
    2691             :         {
    2692          12 :             PrintLine(fpSchema, "            <xs:sequence>");
    2693          12 :             PrintLine(fpSchema,
    2694             :                       "              <xs:element ref=\"gml:_Feature\"/>");
    2695          12 :             PrintLine(fpSchema, "            </xs:sequence>");
    2696             :         }
    2697          87 :         PrintLine(fpSchema, "          </xs:complexType>");
    2698          87 :         PrintLine(fpSchema, "        </xs:element>");
    2699          87 :         PrintLine(fpSchema, "      </xs:sequence>");
    2700          87 :         PrintLine(fpSchema, "    </xs:extension>");
    2701          87 :         PrintLine(fpSchema, "  </xs:complexContent>");
    2702          87 :         PrintLine(fpSchema, "</xs:complexType>");
    2703             :     }
    2704          11 :     else if (!bGMLFeatureCollection)
    2705             :     {
    2706          10 :         PrintLine(fpSchema, "<xs:complexType name=\"FeatureCollectionType\">");
    2707          10 :         PrintLine(fpSchema, "  <xs:complexContent>");
    2708          10 :         PrintLine(
    2709             :             fpSchema,
    2710             :             "    <xs:extension base=\"gml:AbstractFeatureCollectionType\">");
    2711          10 :         PrintLine(fpSchema, "      <xs:attribute name=\"lockId\" "
    2712             :                             "type=\"xs:string\" use=\"optional\"/>");
    2713          10 :         PrintLine(fpSchema, "      <xs:attribute name=\"scope\" "
    2714             :                             "type=\"xs:string\" use=\"optional\"/>");
    2715          10 :         PrintLine(fpSchema, "    </xs:extension>");
    2716          10 :         PrintLine(fpSchema, "  </xs:complexContent>");
    2717          10 :         PrintLine(fpSchema, "</xs:complexType>");
    2718             :     }
    2719             : 
    2720             :     // Define the schema for each layer.
    2721         223 :     for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
    2722             :     {
    2723         125 :         OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
    2724             : 
    2725             :         // Emit initial stuff for a feature type.
    2726         125 :         if (IsGML32Output())
    2727             :         {
    2728          91 :             PrintLine(fpSchema,
    2729             :                       "<xs:element name=\"%s\" type=\"%s:%s_Type\" "
    2730             :                       "substitutionGroup=\"gml:AbstractFeature\"/>",
    2731          91 :                       poFDefn->GetName(), pszPrefix, poFDefn->GetName());
    2732             :         }
    2733             :         else
    2734             :         {
    2735          34 :             PrintLine(fpSchema,
    2736             :                       "<xs:element name=\"%s\" type=\"%s:%s_Type\" "
    2737             :                       "substitutionGroup=\"gml:_Feature\"/>",
    2738          34 :                       poFDefn->GetName(), pszPrefix, poFDefn->GetName());
    2739             :         }
    2740             : 
    2741         125 :         PrintLine(fpSchema, "<xs:complexType name=\"%s_Type\">",
    2742         125 :                   poFDefn->GetName());
    2743         125 :         PrintLine(fpSchema, "  <xs:complexContent>");
    2744         125 :         PrintLine(fpSchema,
    2745             :                   "    <xs:extension base=\"gml:AbstractFeatureType\">");
    2746         125 :         PrintLine(fpSchema, "      <xs:sequence>");
    2747             : 
    2748         248 :         for (int iGeomField = 0; iGeomField < poFDefn->GetGeomFieldCount();
    2749             :              iGeomField++)
    2750             :         {
    2751             :             OGRGeomFieldDefn *poFieldDefn =
    2752         123 :                 poFDefn->GetGeomFieldDefn(iGeomField);
    2753             : 
    2754             :             // Define the geometry attribute.
    2755         123 :             const char *pszGeometryTypeName = "GeometryPropertyType";
    2756         123 :             const char *pszGeomTypeComment = "";
    2757         123 :             OGRwkbGeometryType eGType = wkbFlatten(poFieldDefn->GetType());
    2758         123 :             switch (eGType)
    2759             :             {
    2760          25 :                 case wkbPoint:
    2761          25 :                     pszGeometryTypeName = "PointPropertyType";
    2762          25 :                     break;
    2763          12 :                 case wkbLineString:
    2764             :                 case wkbCircularString:
    2765             :                 case wkbCompoundCurve:
    2766          12 :                     if (IsGML3Output())
    2767             :                     {
    2768          12 :                         if (eGType == wkbLineString)
    2769          11 :                             pszGeomTypeComment =
    2770             :                                 " <!-- restricted to LineString -->";
    2771           1 :                         else if (eGType == wkbCircularString)
    2772           0 :                             pszGeomTypeComment =
    2773             :                                 " <!-- contains CircularString -->";
    2774           1 :                         else if (eGType == wkbCompoundCurve)
    2775           1 :                             pszGeomTypeComment =
    2776             :                                 " <!-- contains CompoundCurve -->";
    2777          12 :                         pszGeometryTypeName = "CurvePropertyType";
    2778             :                     }
    2779             :                     else
    2780           0 :                         pszGeometryTypeName = "LineStringPropertyType";
    2781          12 :                     break;
    2782          16 :                 case wkbPolygon:
    2783             :                 case wkbCurvePolygon:
    2784          16 :                     if (IsGML3Output())
    2785             :                     {
    2786          14 :                         if (eGType == wkbPolygon)
    2787          13 :                             pszGeomTypeComment =
    2788             :                                 " <!-- restricted to Polygon -->";
    2789           1 :                         else if (eGType == wkbCurvePolygon)
    2790           1 :                             pszGeomTypeComment =
    2791             :                                 " <!-- contains CurvePolygon -->";
    2792          14 :                         pszGeometryTypeName = "SurfacePropertyType";
    2793             :                     }
    2794             :                     else
    2795           2 :                         pszGeometryTypeName = "PolygonPropertyType";
    2796          16 :                     break;
    2797           6 :                 case wkbMultiPoint:
    2798           6 :                     pszGeometryTypeName = "MultiPointPropertyType";
    2799           6 :                     break;
    2800           9 :                 case wkbMultiLineString:
    2801             :                 case wkbMultiCurve:
    2802           9 :                     if (IsGML3Output())
    2803             :                     {
    2804           9 :                         if (eGType == wkbMultiLineString)
    2805           8 :                             pszGeomTypeComment =
    2806             :                                 " <!-- restricted to MultiLineString -->";
    2807           1 :                         else if (eGType == wkbMultiCurve)
    2808           1 :                             pszGeomTypeComment =
    2809             :                                 " <!-- contains non-linear MultiCurve -->";
    2810           9 :                         pszGeometryTypeName = "MultiCurvePropertyType";
    2811             :                     }
    2812             :                     else
    2813           0 :                         pszGeometryTypeName = "MultiLineStringPropertyType";
    2814           9 :                     break;
    2815          12 :                 case wkbMultiPolygon:
    2816             :                 case wkbMultiSurface:
    2817          12 :                     if (IsGML3Output())
    2818             :                     {
    2819          11 :                         if (eGType == wkbMultiPolygon)
    2820          10 :                             pszGeomTypeComment =
    2821             :                                 " <!-- restricted to MultiPolygon -->";
    2822           1 :                         else if (eGType == wkbMultiSurface)
    2823           1 :                             pszGeomTypeComment =
    2824             :                                 " <!-- contains non-linear MultiSurface -->";
    2825          11 :                         pszGeometryTypeName = "MultiSurfacePropertyType";
    2826             :                     }
    2827             :                     else
    2828           1 :                         pszGeometryTypeName = "MultiPolygonPropertyType";
    2829          12 :                     break;
    2830           6 :                 case wkbGeometryCollection:
    2831           6 :                     pszGeometryTypeName = "MultiGeometryPropertyType";
    2832           6 :                     break;
    2833          37 :                 default:
    2834          37 :                     break;
    2835             :             }
    2836             : 
    2837         123 :             const auto poSRS = poFieldDefn->GetSpatialRef();
    2838         246 :             std::string osSRSNameComment;
    2839         123 :             if (poSRS)
    2840             :             {
    2841          30 :                 bool bCoordSwap = false;
    2842             :                 char *pszSRSName =
    2843          30 :                     GML_GetSRSName(poSRS, GetSRSNameFormat(), &bCoordSwap);
    2844          30 :                 if (pszSRSName[0])
    2845             :                 {
    2846          30 :                     osSRSNameComment = "<!--";
    2847          30 :                     osSRSNameComment += pszSRSName;
    2848          30 :                     osSRSNameComment += " -->";
    2849             :                 }
    2850          30 :                 CPLFree(pszSRSName);
    2851             :             }
    2852             : 
    2853         123 :             int nMinOccurs = poFieldDefn->IsNullable() ? 0 : 1;
    2854         123 :             const auto &oCoordPrec = poFieldDefn->GetCoordinatePrecision();
    2855         123 :             if (oCoordPrec.dfXYResolution ==
    2856         122 :                     OGRGeomCoordinatePrecision::UNKNOWN &&
    2857         122 :                 oCoordPrec.dfZResolution == OGRGeomCoordinatePrecision::UNKNOWN)
    2858             :             {
    2859         122 :                 PrintLine(
    2860             :                     fpSchema,
    2861             :                     "        <xs:element name=\"%s\" type=\"gml:%s\" "
    2862             :                     "nillable=\"true\" minOccurs=\"%d\" maxOccurs=\"1\"/>%s%s",
    2863             :                     poFieldDefn->GetNameRef(), pszGeometryTypeName, nMinOccurs,
    2864             :                     pszGeomTypeComment, osSRSNameComment.c_str());
    2865             :             }
    2866             :             else
    2867             :             {
    2868           1 :                 PrintLine(fpSchema,
    2869             :                           "        <xs:element name=\"%s\" type=\"gml:%s\" "
    2870             :                           "nillable=\"true\" minOccurs=\"%d\" maxOccurs=\"1\">",
    2871             :                           poFieldDefn->GetNameRef(), pszGeometryTypeName,
    2872             :                           nMinOccurs);
    2873           1 :                 PrintLine(fpSchema, "          <xs:annotation>");
    2874           1 :                 PrintLine(fpSchema, "            <xs:appinfo "
    2875             :                                     "source=\"http://ogr.maptools.org/\">");
    2876           1 :                 if (oCoordPrec.dfXYResolution !=
    2877             :                     OGRGeomCoordinatePrecision::UNKNOWN)
    2878             :                 {
    2879           1 :                     PrintLine(fpSchema,
    2880             :                               "              "
    2881             :                               "<ogr:xy_coordinate_resolution>%g</"
    2882             :                               "ogr:xy_coordinate_resolution>",
    2883           1 :                               oCoordPrec.dfXYResolution);
    2884             :                 }
    2885           1 :                 if (oCoordPrec.dfZResolution !=
    2886             :                     OGRGeomCoordinatePrecision::UNKNOWN)
    2887             :                 {
    2888           1 :                     PrintLine(fpSchema,
    2889             :                               "              "
    2890             :                               "<ogr:z_coordinate_resolution>%g</"
    2891             :                               "ogr:z_coordinate_resolution>",
    2892           1 :                               oCoordPrec.dfZResolution);
    2893             :                 }
    2894           1 :                 PrintLine(fpSchema, "            </xs:appinfo>");
    2895           1 :                 PrintLine(fpSchema, "          </xs:annotation>");
    2896           1 :                 PrintLine(fpSchema, "        </xs:element>%s%s",
    2897             :                           pszGeomTypeComment, osSRSNameComment.c_str());
    2898             :             }
    2899             :         }
    2900             : 
    2901             :         // Emit each of the attributes.
    2902         306 :         for (int iField = 0; iField < poFDefn->GetFieldCount(); iField++)
    2903             :         {
    2904         181 :             OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
    2905             : 
    2906         351 :             if (IsGML3Output() &&
    2907         170 :                 strcmp(poFieldDefn->GetNameRef(), "gml_id") == 0)
    2908           1 :                 continue;
    2909         191 :             else if (!IsGML3Output() &&
    2910          11 :                      strcmp(poFieldDefn->GetNameRef(), "fid") == 0)
    2911           0 :                 continue;
    2912             : 
    2913         202 :             const auto AddComment = [this, fpSchema, poFieldDefn]()
    2914             :             {
    2915         180 :                 if (!poFieldDefn->GetComment().empty())
    2916             :                 {
    2917          11 :                     char *pszComment = CPLEscapeString(
    2918          11 :                         poFieldDefn->GetComment().c_str(), -1, CPLES_XML);
    2919          11 :                     PrintLine(fpSchema,
    2920             :                               "          "
    2921             :                               "<xs:annotation><xs:documentation>%s</"
    2922             :                               "xs:documentation></xs:annotation>",
    2923             :                               pszComment);
    2924          11 :                     CPLFree(pszComment);
    2925             :                 }
    2926         360 :             };
    2927             : 
    2928         180 :             int nMinOccurs = poFieldDefn->IsNullable() ? 0 : 1;
    2929         180 :             const OGRFieldType eType = poFieldDefn->GetType();
    2930         180 :             if (eType == OFTInteger || eType == OFTIntegerList)
    2931             :             {
    2932             :                 int nWidth =
    2933          32 :                     poFieldDefn->GetWidth() > 0 ? poFieldDefn->GetWidth() : 16;
    2934             : 
    2935          32 :                 PrintLine(fpSchema,
    2936             :                           "        <xs:element name=\"%s\" nillable=\"true\" "
    2937             :                           "minOccurs=\"%d\" maxOccurs=\"%s\">",
    2938             :                           poFieldDefn->GetNameRef(), nMinOccurs,
    2939             :                           eType == OFTIntegerList ? "unbounded" : "1");
    2940          32 :                 AddComment();
    2941          32 :                 PrintLine(fpSchema, "          <xs:simpleType>");
    2942          32 :                 if (poFieldDefn->GetSubType() == OFSTBoolean)
    2943             :                 {
    2944           3 :                     PrintLine(
    2945             :                         fpSchema,
    2946             :                         "            <xs:restriction base=\"xs:boolean\">");
    2947             :                 }
    2948          29 :                 else if (poFieldDefn->GetSubType() == OFSTInt16)
    2949             :                 {
    2950           1 :                     PrintLine(fpSchema,
    2951             :                               "            <xs:restriction base=\"xs:short\">");
    2952             :                 }
    2953             :                 else
    2954             :                 {
    2955          28 :                     PrintLine(
    2956             :                         fpSchema,
    2957             :                         "            <xs:restriction base=\"xs:integer\">");
    2958          28 :                     PrintLine(fpSchema,
    2959             :                               "              <xs:totalDigits value=\"%d\"/>",
    2960             :                               nWidth);
    2961             :                 }
    2962          32 :                 PrintLine(fpSchema, "            </xs:restriction>");
    2963          32 :                 PrintLine(fpSchema, "          </xs:simpleType>");
    2964          32 :                 PrintLine(fpSchema, "        </xs:element>");
    2965             :             }
    2966         148 :             else if (eType == OFTInteger64 || eType == OFTInteger64List)
    2967             :             {
    2968             :                 int nWidth =
    2969          17 :                     poFieldDefn->GetWidth() > 0 ? poFieldDefn->GetWidth() : 16;
    2970             : 
    2971          17 :                 PrintLine(fpSchema,
    2972             :                           "        <xs:element name=\"%s\" nillable=\"true\" "
    2973             :                           "minOccurs=\"%d\" maxOccurs=\"%s\">",
    2974             :                           poFieldDefn->GetNameRef(), nMinOccurs,
    2975             :                           eType == OFTInteger64List ? "unbounded" : "1");
    2976          17 :                 AddComment();
    2977          17 :                 PrintLine(fpSchema, "          <xs:simpleType>");
    2978          17 :                 if (poFieldDefn->GetSubType() == OFSTBoolean)
    2979             :                 {
    2980           0 :                     PrintLine(
    2981             :                         fpSchema,
    2982             :                         "            <xs:restriction base=\"xs:boolean\">");
    2983             :                 }
    2984          17 :                 else if (poFieldDefn->GetSubType() == OFSTInt16)
    2985             :                 {
    2986           0 :                     PrintLine(fpSchema,
    2987             :                               "            <xs:restriction base=\"xs:short\">");
    2988             :                 }
    2989             :                 else
    2990             :                 {
    2991          17 :                     PrintLine(fpSchema,
    2992             :                               "            <xs:restriction base=\"xs:long\">");
    2993          17 :                     PrintLine(fpSchema,
    2994             :                               "              <xs:totalDigits value=\"%d\"/>",
    2995             :                               nWidth);
    2996             :                 }
    2997          17 :                 PrintLine(fpSchema, "            </xs:restriction>");
    2998          17 :                 PrintLine(fpSchema, "          </xs:simpleType>");
    2999          17 :                 PrintLine(fpSchema, "        </xs:element>");
    3000             :             }
    3001         131 :             else if (eType == OFTReal || eType == OFTRealList)
    3002             :             {
    3003             :                 int nWidth, nDecimals;
    3004             : 
    3005          35 :                 nWidth = poFieldDefn->GetWidth();
    3006          35 :                 nDecimals = poFieldDefn->GetPrecision();
    3007             : 
    3008          35 :                 PrintLine(fpSchema,
    3009             :                           "        <xs:element name=\"%s\" nillable=\"true\" "
    3010             :                           "minOccurs=\"%d\" maxOccurs=\"%s\">",
    3011             :                           poFieldDefn->GetNameRef(), nMinOccurs,
    3012             :                           eType == OFTRealList ? "unbounded" : "1");
    3013          35 :                 AddComment();
    3014          35 :                 PrintLine(fpSchema, "          <xs:simpleType>");
    3015          35 :                 if (poFieldDefn->GetSubType() == OFSTFloat32)
    3016           1 :                     PrintLine(fpSchema,
    3017             :                               "            <xs:restriction base=\"xs:float\">");
    3018             :                 else
    3019          34 :                     PrintLine(
    3020             :                         fpSchema,
    3021             :                         "            <xs:restriction base=\"xs:decimal\">");
    3022          35 :                 if (nWidth > 0)
    3023             :                 {
    3024          14 :                     PrintLine(fpSchema,
    3025             :                               "              <xs:totalDigits value=\"%d\"/>",
    3026             :                               nWidth);
    3027          14 :                     PrintLine(fpSchema,
    3028             :                               "              <xs:fractionDigits value=\"%d\"/>",
    3029             :                               nDecimals);
    3030             :                 }
    3031          35 :                 PrintLine(fpSchema, "            </xs:restriction>");
    3032          35 :                 PrintLine(fpSchema, "          </xs:simpleType>");
    3033          35 :                 PrintLine(fpSchema, "        </xs:element>");
    3034             :             }
    3035          96 :             else if (eType == OFTString || eType == OFTStringList)
    3036             :             {
    3037          58 :                 PrintLine(fpSchema,
    3038             :                           "        <xs:element name=\"%s\" nillable=\"true\" "
    3039             :                           "minOccurs=\"%d\" maxOccurs=\"%s\">",
    3040             :                           poFieldDefn->GetNameRef(), nMinOccurs,
    3041             :                           eType == OFTStringList ? "unbounded" : "1");
    3042          58 :                 AddComment();
    3043          58 :                 PrintLine(fpSchema, "          <xs:simpleType>");
    3044          58 :                 PrintLine(fpSchema,
    3045             :                           "            <xs:restriction base=\"xs:string\">");
    3046          58 :                 if (poFieldDefn->GetWidth() != 0)
    3047             :                 {
    3048          10 :                     PrintLine(fpSchema,
    3049             :                               "              <xs:maxLength value=\"%d\"/>",
    3050             :                               poFieldDefn->GetWidth());
    3051             :                 }
    3052          58 :                 PrintLine(fpSchema, "            </xs:restriction>");
    3053          58 :                 PrintLine(fpSchema, "          </xs:simpleType>");
    3054          58 :                 PrintLine(fpSchema, "        </xs:element>");
    3055             :             }
    3056          38 :             else if (eType == OFTDate)
    3057             :             {
    3058          18 :                 PrintLine(fpSchema,
    3059             :                           "        <xs:element name=\"%s\" nillable=\"true\" "
    3060             :                           "minOccurs=\"%d\" maxOccurs=\"1\" type=\"xs:date\">",
    3061             :                           poFieldDefn->GetNameRef(), nMinOccurs);
    3062          18 :                 AddComment();
    3063          18 :                 PrintLine(fpSchema, "        </xs:element>");
    3064             :             }
    3065          20 :             else if (eType == OFTTime)
    3066             :             {
    3067           2 :                 PrintLine(fpSchema,
    3068             :                           "        <xs:element name=\"%s\" nillable=\"true\" "
    3069             :                           "minOccurs=\"%d\" maxOccurs=\"1\" type=\"xs:time\">",
    3070             :                           poFieldDefn->GetNameRef(), nMinOccurs);
    3071           2 :                 AddComment();
    3072           2 :                 PrintLine(fpSchema, "        </xs:element>");
    3073             :             }
    3074          18 :             else if (eType == OFTDateTime)
    3075             :             {
    3076          18 :                 PrintLine(
    3077             :                     fpSchema,
    3078             :                     "        <xs:element name=\"%s\" nillable=\"true\" "
    3079             :                     "minOccurs=\"%d\" maxOccurs=\"1\" type=\"xs:dateTime\">",
    3080             :                     poFieldDefn->GetNameRef(), nMinOccurs);
    3081          18 :                 AddComment();
    3082          18 :                 PrintLine(fpSchema, "        </xs:element>");
    3083             :             }
    3084             :             else
    3085             :             {
    3086             :                 // TODO.
    3087             :             }
    3088             :         }  // Next field.
    3089             : 
    3090             :         // Finish off feature type.
    3091         125 :         PrintLine(fpSchema, "      </xs:sequence>");
    3092         125 :         PrintLine(fpSchema, "    </xs:extension>");
    3093         125 :         PrintLine(fpSchema, "  </xs:complexContent>");
    3094         125 :         PrintLine(fpSchema, "</xs:complexType>");
    3095             :     }  // Next layer.
    3096             : 
    3097          98 :     PrintLine(fpSchema, "</xs:schema>");
    3098             : 
    3099             :     // Move schema to the start of the file.
    3100          98 :     if (fpSchema == fpOutput)
    3101             :     {
    3102             :         // Read the schema into memory.
    3103           0 :         int nSchemaSize = static_cast<int>(VSIFTellL(fpSchema) - nSchemaStart);
    3104           0 :         char *pszSchema = static_cast<char *>(CPLMalloc(nSchemaSize + 1));
    3105             : 
    3106           0 :         VSIFSeekL(fpSchema, nSchemaStart, SEEK_SET);
    3107             : 
    3108           0 :         VSIFReadL(pszSchema, 1, nSchemaSize, fpSchema);
    3109           0 :         pszSchema[nSchemaSize] = '\0';
    3110             : 
    3111             :         // Move file data down by "schema size" bytes from after <?xml> header
    3112             :         // so we have room insert the schema.  Move in pretty big chunks.
    3113           0 :         int nChunkSize = std::min(nSchemaStart - nSchemaInsertLocation, 250000);
    3114           0 :         char *pszChunk = static_cast<char *>(CPLMalloc(nChunkSize));
    3115             : 
    3116           0 :         for (int nEndOfUnmovedData = nSchemaStart;
    3117           0 :              nEndOfUnmovedData > nSchemaInsertLocation;)
    3118             :         {
    3119             :             const int nBytesToMove =
    3120           0 :                 std::min(nChunkSize, nEndOfUnmovedData - nSchemaInsertLocation);
    3121             : 
    3122           0 :             VSIFSeekL(fpSchema, nEndOfUnmovedData - nBytesToMove, SEEK_SET);
    3123           0 :             VSIFReadL(pszChunk, 1, nBytesToMove, fpSchema);
    3124           0 :             VSIFSeekL(fpSchema, nEndOfUnmovedData - nBytesToMove + nSchemaSize,
    3125             :                       SEEK_SET);
    3126           0 :             VSIFWriteL(pszChunk, 1, nBytesToMove, fpSchema);
    3127             : 
    3128           0 :             nEndOfUnmovedData -= nBytesToMove;
    3129             :         }
    3130             : 
    3131           0 :         CPLFree(pszChunk);
    3132             : 
    3133             :         // Write the schema in the opened slot.
    3134           0 :         VSIFSeekL(fpSchema, nSchemaInsertLocation, SEEK_SET);
    3135           0 :         VSIFWriteL(pszSchema, 1, nSchemaSize, fpSchema);
    3136             : 
    3137           0 :         VSIFSeekL(fpSchema, 0, SEEK_END);
    3138             : 
    3139           0 :         nBoundedByLocation += nSchemaSize;
    3140             : 
    3141           0 :         CPLFree(pszSchema);
    3142             :     }
    3143             :     else
    3144             :     {
    3145             :         // Close external schema files.
    3146          98 :         VSIFCloseL(fpSchema);
    3147             :     }
    3148             : }
    3149             : 
    3150             : /************************************************************************/
    3151             : /*                            PrintLine()                               */
    3152             : /************************************************************************/
    3153             : 
    3154        8564 : void OGRGMLDataSource::PrintLine(VSILFILE *fp, const char *fmt, ...)
    3155             : {
    3156       17128 :     CPLString osWork;
    3157             :     va_list args;
    3158             : 
    3159        8564 :     va_start(args, fmt);
    3160        8564 :     osWork.vPrintf(fmt, args);
    3161        8564 :     va_end(args);
    3162             : 
    3163             : #ifdef _WIN32
    3164             :     constexpr const char *pszEOL = "\r\n";
    3165             : #else
    3166        8564 :     constexpr const char *pszEOL = "\n";
    3167             : #endif
    3168             : 
    3169       17123 :     if (VSIFWriteL(osWork.data(), osWork.size(), 1, fp) != 1 ||
    3170        8559 :         VSIFWriteL(pszEOL, strlen(pszEOL), 1, fp) != 1)
    3171             :     {
    3172           5 :         m_bWriteError = true;
    3173           5 :         ReportError(CE_Failure, CPLE_FileIO, "Could not write line %s",
    3174             :                     osWork.c_str());
    3175             :     }
    3176        8564 : }
    3177             : 
    3178             : /************************************************************************/
    3179             : /*                     OGRGMLSingleFeatureLayer                         */
    3180             : /************************************************************************/
    3181             : 
    3182             : class OGRGMLSingleFeatureLayer final : public OGRLayer
    3183             : {
    3184             :   private:
    3185             :     const int nVal;
    3186             :     OGRFeatureDefn *poFeatureDefn = nullptr;
    3187             :     int iNextShapeId = 0;
    3188             : 
    3189             :     CPL_DISALLOW_COPY_ASSIGN(OGRGMLSingleFeatureLayer)
    3190             : 
    3191             :   public:
    3192             :     explicit OGRGMLSingleFeatureLayer(int nVal);
    3193             : 
    3194           0 :     ~OGRGMLSingleFeatureLayer() override
    3195           0 :     {
    3196           0 :         poFeatureDefn->Release();
    3197           0 :     }
    3198             : 
    3199           0 :     void ResetReading() override
    3200             :     {
    3201           0 :         iNextShapeId = 0;
    3202           0 :     }
    3203             : 
    3204             :     OGRFeature *GetNextFeature() override;
    3205             : 
    3206           0 :     const OGRFeatureDefn *GetLayerDefn() const override
    3207             :     {
    3208           0 :         return poFeatureDefn;
    3209             :     }
    3210             : 
    3211           0 :     int TestCapability(const char *) const override
    3212             :     {
    3213           0 :         return FALSE;
    3214             :     }
    3215             : };
    3216             : 
    3217             : /************************************************************************/
    3218             : /*                      OGRGMLSingleFeatureLayer()                      */
    3219             : /************************************************************************/
    3220             : 
    3221           0 : OGRGMLSingleFeatureLayer::OGRGMLSingleFeatureLayer(int nValIn)
    3222           0 :     : nVal(nValIn), poFeatureDefn(new OGRFeatureDefn("SELECT")), iNextShapeId(0)
    3223             : {
    3224           0 :     poFeatureDefn->Reference();
    3225           0 :     OGRFieldDefn oField("Validates", OFTInteger);
    3226           0 :     poFeatureDefn->AddFieldDefn(&oField);
    3227           0 : }
    3228             : 
    3229             : /************************************************************************/
    3230             : /*                           GetNextFeature()                           */
    3231             : /************************************************************************/
    3232             : 
    3233           0 : OGRFeature *OGRGMLSingleFeatureLayer::GetNextFeature()
    3234             : {
    3235           0 :     if (iNextShapeId != 0)
    3236           0 :         return nullptr;
    3237             : 
    3238           0 :     OGRFeature *poFeature = new OGRFeature(poFeatureDefn);
    3239           0 :     poFeature->SetField(0, nVal);
    3240           0 :     poFeature->SetFID(iNextShapeId++);
    3241           0 :     return poFeature;
    3242             : }
    3243             : 
    3244             : /************************************************************************/
    3245             : /*                            ExecuteSQL()                              */
    3246             : /************************************************************************/
    3247             : 
    3248           6 : OGRLayer *OGRGMLDataSource::ExecuteSQL(const char *pszSQLCommand,
    3249             :                                        OGRGeometry *poSpatialFilter,
    3250             :                                        const char *pszDialect)
    3251             : {
    3252           6 :     if (poReader != nullptr && EQUAL(pszSQLCommand, "SELECT ValidateSchema()"))
    3253             :     {
    3254           0 :         bool bIsValid = false;
    3255           0 :         if (!osXSDFilename.empty())
    3256             :         {
    3257           0 :             CPLErrorReset();
    3258             :             bIsValid =
    3259           0 :                 CPL_TO_BOOL(CPLValidateXML(osFilename, osXSDFilename, nullptr));
    3260             :         }
    3261           0 :         return new OGRGMLSingleFeatureLayer(bIsValid);
    3262             :     }
    3263             : 
    3264           6 :     return GDALDataset::ExecuteSQL(pszSQLCommand, poSpatialFilter, pszDialect);
    3265             : }
    3266             : 
    3267             : /************************************************************************/
    3268             : /*                          ReleaseResultSet()                          */
    3269             : /************************************************************************/
    3270             : 
    3271           5 : void OGRGMLDataSource::ReleaseResultSet(OGRLayer *poResultsSet)
    3272             : {
    3273           5 :     delete poResultsSet;
    3274           5 : }
    3275             : 
    3276             : /************************************************************************/
    3277             : /*                      FindAndParseTopElements()                       */
    3278             : /************************************************************************/
    3279             : 
    3280         447 : void OGRGMLDataSource::FindAndParseTopElements(VSILFILE *fp)
    3281             : {
    3282             :     // Build a shortened XML file that contain only the global
    3283             :     // boundedBy element, so as to be able to parse it easily.
    3284             : 
    3285             :     char szStartTag[128];
    3286         447 :     char *pszXML = static_cast<char *>(CPLMalloc(8192 + 128 + 3 + 1));
    3287         447 :     VSIFSeekL(fp, 0, SEEK_SET);
    3288         447 :     int nRead = static_cast<int>(VSIFReadL(pszXML, 1, 8192, fp));
    3289         447 :     pszXML[nRead] = 0;
    3290             : 
    3291         447 :     const char *pszStartTag = strchr(pszXML, '<');
    3292         447 :     if (pszStartTag != nullptr)
    3293             :     {
    3294         815 :         while (pszStartTag != nullptr && pszStartTag[1] == '?')
    3295         368 :             pszStartTag = strchr(pszStartTag + 1, '<');
    3296             : 
    3297         447 :         if (pszStartTag != nullptr)
    3298             :         {
    3299         447 :             pszStartTag++;
    3300         447 :             const char *pszEndTag = nullptr;
    3301        9547 :             for (const char *pszIter = pszStartTag; *pszIter != '\0'; pszIter++)
    3302             :             {
    3303        9547 :                 if (isspace(static_cast<unsigned char>(*pszIter)) ||
    3304        9102 :                     *pszIter == '>')
    3305             :                 {
    3306         447 :                     pszEndTag = pszIter;
    3307         447 :                     break;
    3308             :                 }
    3309             :             }
    3310         447 :             if (pszEndTag != nullptr && pszEndTag - pszStartTag < 128)
    3311             :             {
    3312         447 :                 memcpy(szStartTag, pszStartTag, pszEndTag - pszStartTag);
    3313         447 :                 szStartTag[pszEndTag - pszStartTag] = '\0';
    3314             :             }
    3315             :             else
    3316           0 :                 pszStartTag = nullptr;
    3317             :         }
    3318             :     }
    3319             : 
    3320         447 :     const char *pszFeatureMember = strstr(pszXML, "<gml:featureMember");
    3321         447 :     if (pszFeatureMember == nullptr)
    3322         280 :         pszFeatureMember = strstr(pszXML, ":featureMember>");
    3323         447 :     if (pszFeatureMember == nullptr)
    3324         169 :         pszFeatureMember = strstr(pszXML, "<wfs:member>");
    3325             : 
    3326             :     // Is it a standalone geometry ?
    3327         447 :     if (pszFeatureMember == nullptr && pszStartTag != nullptr)
    3328             :     {
    3329         107 :         const char *pszElement = szStartTag;
    3330         107 :         const char *pszColon = strchr(pszElement, ':');
    3331         107 :         if (pszColon)
    3332          73 :             pszElement = pszColon + 1;
    3333         107 :         if (OGRGMLIsGeometryElement(pszElement))
    3334             :         {
    3335           1 :             VSIFSeekL(fp, 0, SEEK_END);
    3336           1 :             const auto nLen = VSIFTellL(fp);
    3337           1 :             if (nLen < 10 * 1024 * 1024U)
    3338             :             {
    3339           1 :                 VSIFSeekL(fp, 0, SEEK_SET);
    3340           2 :                 std::string osBuffer;
    3341             :                 try
    3342             :                 {
    3343           1 :                     osBuffer.resize(static_cast<size_t>(nLen));
    3344           1 :                     VSIFReadL(&osBuffer[0], 1, osBuffer.size(), fp);
    3345             :                 }
    3346           0 :                 catch (const std::exception &)
    3347             :                 {
    3348             :                 }
    3349           1 :                 CPLPushErrorHandler(CPLQuietErrorHandler);
    3350           1 :                 CPLXMLNode *psTree = CPLParseXMLString(osBuffer.data());
    3351           1 :                 CPLPopErrorHandler();
    3352           1 :                 CPLErrorReset();
    3353           1 :                 if (psTree)
    3354             :                 {
    3355           1 :                     m_poStandaloneGeom.reset(GML2OGRGeometry_XMLNode(
    3356             :                         psTree, false, 0, 0, false, true, false));
    3357             : 
    3358           1 :                     if (m_poStandaloneGeom)
    3359             :                     {
    3360           2 :                         for (CPLXMLNode *psCur = psTree; psCur;
    3361           1 :                              psCur = psCur->psNext)
    3362             :                         {
    3363           2 :                             if (psCur->eType == CXT_Element &&
    3364           2 :                                 strcmp(psCur->pszValue, szStartTag) == 0)
    3365             :                             {
    3366             :                                 const char *pszSRSName =
    3367           1 :                                     CPLGetXMLValue(psCur, "srsName", nullptr);
    3368           1 :                                 if (pszSRSName)
    3369             :                                 {
    3370           1 :                                     m_oStandaloneGeomSRS.SetFromUserInput(
    3371             :                                         pszSRSName,
    3372             :                                         OGRSpatialReference::
    3373             :                                             SET_FROM_USER_INPUT_LIMITATIONS_get());
    3374           1 :                                     m_oStandaloneGeomSRS.SetAxisMappingStrategy(
    3375             :                                         OAMS_TRADITIONAL_GIS_ORDER);
    3376           1 :                                     if (GML_IsSRSLatLongOrder(pszSRSName))
    3377           1 :                                         m_poStandaloneGeom->swapXY();
    3378             :                                 }
    3379           1 :                                 break;
    3380             :                             }
    3381             :                         }
    3382             :                     }
    3383           1 :                     CPLDestroyXMLNode(psTree);
    3384             :                 }
    3385             :             }
    3386             :         }
    3387             :     }
    3388             : 
    3389         447 :     const char *pszDescription = strstr(pszXML, "<gml:description>");
    3390         447 :     if (pszDescription &&
    3391           1 :         (pszFeatureMember == nullptr || pszDescription < pszFeatureMember))
    3392             :     {
    3393           9 :         pszDescription += strlen("<gml:description>");
    3394             :         const char *pszEndDescription =
    3395           9 :             strstr(pszDescription, "</gml:description>");
    3396           9 :         if (pszEndDescription)
    3397             :         {
    3398          18 :             CPLString osTmp(pszDescription);
    3399           9 :             osTmp.resize(pszEndDescription - pszDescription);
    3400           9 :             char *pszTmp = CPLUnescapeString(osTmp, nullptr, CPLES_XML);
    3401           9 :             if (pszTmp)
    3402           9 :                 SetMetadataItem("DESCRIPTION", pszTmp);
    3403           9 :             CPLFree(pszTmp);
    3404             :         }
    3405             :     }
    3406             : 
    3407         447 :     const char *l_pszName = strstr(pszXML, "<gml:name");
    3408         447 :     if (l_pszName)
    3409          12 :         l_pszName = strchr(l_pszName, '>');
    3410         447 :     if (l_pszName &&
    3411           4 :         (pszFeatureMember == nullptr || l_pszName < pszFeatureMember))
    3412             :     {
    3413           9 :         l_pszName++;
    3414           9 :         const char *pszEndName = strstr(l_pszName, "</gml:name>");
    3415           9 :         if (pszEndName)
    3416             :         {
    3417          18 :             CPLString osTmp(l_pszName);
    3418           9 :             osTmp.resize(pszEndName - l_pszName);
    3419           9 :             char *pszTmp = CPLUnescapeString(osTmp, nullptr, CPLES_XML);
    3420           9 :             if (pszTmp)
    3421           9 :                 SetMetadataItem("NAME", pszTmp);
    3422           9 :             CPLFree(pszTmp);
    3423             :         }
    3424             :     }
    3425             : 
    3426             :     // Detect a few fields in gml: namespace inside features
    3427         447 :     if (pszFeatureMember)
    3428             :     {
    3429         340 :         if (strstr(pszFeatureMember, "<gml:description>"))
    3430           1 :             m_aosGMLExtraElements.push_back("description");
    3431         340 :         if (strstr(pszFeatureMember, "<gml:identifier>") ||
    3432         340 :             strstr(pszFeatureMember, "<gml:identifier "))
    3433           1 :             m_aosGMLExtraElements.push_back("identifier");
    3434         340 :         if (strstr(pszFeatureMember, "<gml:name>") ||
    3435         336 :             strstr(pszFeatureMember, "<gml:name "))
    3436           4 :             m_aosGMLExtraElements.push_back("name");
    3437             :     }
    3438             : 
    3439         447 :     char *pszEndBoundedBy = strstr(pszXML, "</wfs:boundedBy>");
    3440         447 :     bool bWFSBoundedBy = false;
    3441         447 :     if (pszEndBoundedBy != nullptr)
    3442           2 :         bWFSBoundedBy = true;
    3443             :     else
    3444         445 :         pszEndBoundedBy = strstr(pszXML, "</gml:boundedBy>");
    3445         447 :     if (pszStartTag != nullptr && pszEndBoundedBy != nullptr)
    3446             :     {
    3447         225 :         char szSRSName[128] = {};
    3448             : 
    3449             :         // Find a srsName somewhere for some WFS 2.0 documents that have not it
    3450             :         // set at the <wfs:boundedBy> element. e.g.
    3451             :         // http://geoserv.weichand.de:8080/geoserver/wfs?SERVICE=WFS&REQUEST=GetFeature&VERSION=2.0.0&TYPENAME=bvv:gmd_ex
    3452         225 :         if (bIsWFS)
    3453             :         {
    3454          24 :             ExtractSRSName(pszXML, szSRSName, sizeof(szSRSName));
    3455             :         }
    3456             : 
    3457         225 :         pszEndBoundedBy[strlen("</gml:boundedBy>")] = '\0';
    3458         225 :         strcat(pszXML, "</");
    3459         225 :         strcat(pszXML, szStartTag);
    3460         225 :         strcat(pszXML, ">");
    3461             : 
    3462         225 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    3463         225 :         CPLXMLNode *psXML = CPLParseXMLString(pszXML);
    3464         225 :         CPLPopErrorHandler();
    3465         225 :         CPLErrorReset();
    3466         225 :         if (psXML != nullptr)
    3467             :         {
    3468         220 :             CPLXMLNode *psBoundedBy = nullptr;
    3469         220 :             CPLXMLNode *psIter = psXML;
    3470         436 :             while (psIter != nullptr)
    3471             :             {
    3472         436 :                 psBoundedBy = CPLGetXMLNode(
    3473             :                     psIter, bWFSBoundedBy ? "wfs:boundedBy" : "gml:boundedBy");
    3474         436 :                 if (psBoundedBy != nullptr)
    3475         220 :                     break;
    3476         216 :                 psIter = psIter->psNext;
    3477             :             }
    3478             : 
    3479         220 :             const char *pszLowerCorner = nullptr;
    3480         220 :             const char *pszUpperCorner = nullptr;
    3481         220 :             const char *pszSRSName = nullptr;
    3482         220 :             if (psBoundedBy != nullptr)
    3483             :             {
    3484             :                 CPLXMLNode *psEnvelope =
    3485         220 :                     CPLGetXMLNode(psBoundedBy, "gml:Envelope");
    3486         220 :                 if (psEnvelope)
    3487             :                 {
    3488         114 :                     pszSRSName = CPLGetXMLValue(psEnvelope, "srsName", nullptr);
    3489             :                     pszLowerCorner =
    3490         114 :                         CPLGetXMLValue(psEnvelope, "gml:lowerCorner", nullptr);
    3491             :                     pszUpperCorner =
    3492         114 :                         CPLGetXMLValue(psEnvelope, "gml:upperCorner", nullptr);
    3493             :                 }
    3494             :             }
    3495             : 
    3496         220 :             if (bIsWFS && pszSRSName == nullptr && pszLowerCorner != nullptr &&
    3497           0 :                 pszUpperCorner != nullptr && szSRSName[0] != '\0')
    3498             :             {
    3499           0 :                 pszSRSName = szSRSName;
    3500             :             }
    3501             : 
    3502         220 :             if (pszSRSName != nullptr && pszLowerCorner != nullptr &&
    3503             :                 pszUpperCorner != nullptr)
    3504             :             {
    3505          62 :                 char **papszLC = CSLTokenizeString(pszLowerCorner);
    3506          62 :                 char **papszUC = CSLTokenizeString(pszUpperCorner);
    3507          62 :                 if (CSLCount(papszLC) >= 2 && CSLCount(papszUC) >= 2)
    3508             :                 {
    3509          62 :                     CPLDebug("GML", "Global SRS = %s", pszSRSName);
    3510             : 
    3511          62 :                     if (STARTS_WITH(pszSRSName,
    3512             :                                     "http://www.opengis.net/gml/srs/epsg.xml#"))
    3513             :                     {
    3514           0 :                         std::string osWork;
    3515           0 :                         osWork.assign("EPSG:", 5);
    3516           0 :                         osWork.append(pszSRSName + 40);
    3517           0 :                         poReader->SetGlobalSRSName(osWork.c_str());
    3518             :                     }
    3519             :                     else
    3520             :                     {
    3521          62 :                         poReader->SetGlobalSRSName(pszSRSName);
    3522             :                     }
    3523             : 
    3524          62 :                     const double dfMinX = CPLAtofM(papszLC[0]);
    3525          62 :                     const double dfMinY = CPLAtofM(papszLC[1]);
    3526          62 :                     const double dfMaxX = CPLAtofM(papszUC[0]);
    3527          62 :                     const double dfMaxY = CPLAtofM(papszUC[1]);
    3528             : 
    3529          62 :                     SetExtents(dfMinX, dfMinY, dfMaxX, dfMaxY);
    3530             :                 }
    3531          62 :                 CSLDestroy(papszLC);
    3532          62 :                 CSLDestroy(papszUC);
    3533             :             }
    3534             : 
    3535         220 :             CPLDestroyXMLNode(psXML);
    3536             :         }
    3537             :     }
    3538             : 
    3539         447 :     CPLFree(pszXML);
    3540         447 : }
    3541             : 
    3542             : /************************************************************************/
    3543             : /*                             SetExtents()                             */
    3544             : /************************************************************************/
    3545             : 
    3546          62 : void OGRGMLDataSource::SetExtents(double dfMinX, double dfMinY, double dfMaxX,
    3547             :                                   double dfMaxY)
    3548             : {
    3549          62 :     sBoundingRect.MinX = dfMinX;
    3550          62 :     sBoundingRect.MinY = dfMinY;
    3551          62 :     sBoundingRect.MaxX = dfMaxX;
    3552          62 :     sBoundingRect.MaxY = dfMaxY;
    3553          62 : }
    3554             : 
    3555             : /************************************************************************/
    3556             : /*                             GetAppPrefix()                           */
    3557             : /************************************************************************/
    3558             : 
    3559        1100 : const char *OGRGMLDataSource::GetAppPrefix() const
    3560             : {
    3561        1100 :     return CSLFetchNameValueDef(papszCreateOptions, "PREFIX", "ogr");
    3562             : }
    3563             : 
    3564             : /************************************************************************/
    3565             : /*                            RemoveAppPrefix()                         */
    3566             : /************************************************************************/
    3567             : 
    3568         563 : bool OGRGMLDataSource::RemoveAppPrefix() const
    3569             : {
    3570         563 :     if (CPLTestBool(
    3571         563 :             CSLFetchNameValueDef(papszCreateOptions, "STRIP_PREFIX", "FALSE")))
    3572          26 :         return true;
    3573         537 :     const char *pszPrefix = GetAppPrefix();
    3574         537 :     return pszPrefix[0] == '\0';
    3575             : }
    3576             : 
    3577             : /************************************************************************/
    3578             : /*                        WriteFeatureBoundedBy()                       */
    3579             : /************************************************************************/
    3580             : 
    3581         181 : bool OGRGMLDataSource::WriteFeatureBoundedBy() const
    3582             : {
    3583         181 :     return CPLTestBool(CSLFetchNameValueDef(
    3584         362 :         papszCreateOptions, "WRITE_FEATURE_BOUNDED_BY", "TRUE"));
    3585             : }
    3586             : 
    3587             : /************************************************************************/
    3588             : /*                          GetSRSDimensionLoc()                        */
    3589             : /************************************************************************/
    3590             : 
    3591         215 : const char *OGRGMLDataSource::GetSRSDimensionLoc() const
    3592             : {
    3593         215 :     return CSLFetchNameValue(papszCreateOptions, "SRSDIMENSION_LOC");
    3594             : }
    3595             : 
    3596             : /************************************************************************/
    3597             : /*                        GMLFeatureCollection()                     */
    3598             : /************************************************************************/
    3599             : 
    3600         564 : bool OGRGMLDataSource::GMLFeatureCollection() const
    3601             : {
    3602        1064 :     return IsGML3Output() &&
    3603        1064 :            CPLFetchBool(papszCreateOptions, "GML_FEATURE_COLLECTION", false);
    3604             : }

Generated by: LCOV version 1.14