如何将Geoserver WFS返回的XML/GML响应转换为可访问的JSON/数组格式
解决方案
方案1:直接请求GeoServer返回JSON格式(推荐)
不需要手动解析XML,仅需修改请求参数中的outputFormat取值,GeoServer原生支持直接返回标准GeoJSON格式数据,是成本最低的实现方式:
function filter() { var demande = new XMLHttpRequest(); // 仅需将原有url中的outputFormat参数从GML2修改为application/json var url ='http://localhost:8080/geoserver/wfs?request=GetFeature&version=1.1.0&typeName=topp:refer_22&propertyName=Name,maticha&outputFormat=application/json&FILTER=%3CFilter%20xmlns=%22http://www.opengis.net/ogc%22%3E%3CPropertyIsBetween%3E%3CPropertyName%3Etopp:maticha%3C/PropertyName%3E%3CLowerBoundary%3E%3CLiteral%3E4500%3C/Literal%3E%3C/LowerBoundary%3E%3CUpperBoundary%3E%3CLiteral%3E5000%3C/Literal%3E%3C/UpperBoundary%3E%3C/PropertyIsBetween%3E%3C/Filter%3E' demande.open("GET", url); demande.onload=() => { // 将返回结果转成可直接访问的JSON对象 const geojsonData = JSON.parse(demande.response); // 直接按结构取值即可 const coordinateList = geojsonData.features[0].geometry.coordinates; // 第一个要素的坐标列表 const matichaValue = geojsonData.features[0].properties.maticha; // 第一个要素的maticha字段值 const nameValue = geojsonData.features[0].properties.Name; // 第一个要素的Name字段值 console.log(coordinateList, matichaValue, nameValue); } demande.send(); }
方案2:手动解析GML格式XML响应(仅适用于必须保留GML2输出格式的场景)
如果因业务限制不能修改输出格式,可以用浏览器原生的DOMParser解析XML字符串,手动提取所需字段组装成可用结构:
demande.onload=() => { // 初始化XML解析器 const xmlParser = new DOMParser(); const xmlDoc = xmlParser.parseFromString(demande.response, "text/xml"); const resultList = []; // 提取所有要素节点 const featureNodes = xmlDoc.getElementsByTagName("gml:featureMember"); for(let i=0; i<featureNodes.length; i++) { const currentFeature = featureNodes[i]; // 提取属性字段 const name = currentFeature.getElementsByTagName("topp:Name")[0].textContent; const maticha = Number(currentFeature.getElementsByTagName("topp:maticha")[0].textContent); // 提取坐标字符串并转为二维数组 const coordStr = currentFeature.getElementsByTagName("gml:coordinates")[0].textContent; const coordinates = coordStr.split(" ").map(pointStr => { const [lng, lat] = pointStr.split(",").map(Number); return [lng, lat]; }); // 组装为统一结构存入结果数组 resultList.push({ properties: { name, maticha }, geometry: { type: "MultiPolygon", coordinates: [coordinates] } }) } // 直接访问结果数组即可 const firstCoordinate = resultList[0].geometry.coordinates; console.log(resultList, firstCoordinate); }
注:该方案需要根据实际返回的XML标签命名、几何类型做对应调整。
内容的提问来源于stack exchange,提问作者obito M
相关产品推荐
相关产品推荐

