如何使用正则表达式解析xml节点?

时间:2020-10-05 07:37:51

标签: javascript xml coordinates

我来自aj​​ax的xml响应是

<gml:Polygon srsName="http://www.opengis.net/gml/srs/epsg.xml#3857">
  <gml:outerBoundaryIs>
    <gml:LinearRing>
       <gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">33.36,49.79 33.7410766436,49.788 33.17,49.09 33.62,49.16 33.07,49.46 33.36,49.79</gml:coordinates>
    </gml:LinearRing>
  </gml:outerBoundaryIs>
</gml:Polygon>

我想在<gml:coordinates>节点中获取坐标。

我可以使用正则表达式或其他方法获取坐标值吗?

1 个答案:

答案 0 :(得分:1)

var text = '<gml:Polygon srsName="http://www.opengis.net/gml/srs/epsg.xml#3857">'
+ '<gml:outerBoundaryIs>'
+ '<gml:LinearRing>'
+ '<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">33.36,49.79 33.7410766436,49.788 33.17,49.09 33.62,49.16 33.07,49.46 33.36,49.79</gml:coordinates>'
+ '</gml:LinearRing>'
+ '</gml:outerBoundaryIs>'
+ '</gml:Polygon>';

// parse xml
var parser = new DOMParser();
var doc = parser.parseFromString(text,"text/xml");
// extract node using XPath
var node = doc.evaluate('//*[local-name()="coordinates"]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
// get node text
console.log(node.textContent);