LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gml - ogrgmldatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1536 1719 89.4 %
Date: 2025-10-21 01:37:22 Functions: 34 41 82.9 %

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

Generated by: LCOV version 1.14