-1

My xml response that comes from ajax is

<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>

And I want to get coordinates in <gml:coordinates> node.

Can I get the coordinate values using regex or any other way?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
barteloma
  • 6,403
  • 14
  • 79
  • 173
  • 1
    Have you tried this approach: https://stackoverflow.com/questions/5415452/how-to-extract-values-from-an-xml-document-using-javascript. Using regex can be difficult to maintain. Maybe this: https://stackoverflow.com/questions/7949752/cross-browser-javascript-xml-parsing – Rajesh Oct 05 '20 at 07:41
  • 3
    Do not use regex! Use xml parser. – Maciej Los Oct 05 '20 at 07:50
  • XML is not meant to be parsed via RegEx. While it, physically, is a text file, this text is more to be seen as source code, that describes a tree. This is why one should use an XML parser, which then allows access to the in-memory tree via different means. However, sometimes it is just overdose to use a parser and small, quick tasks could be done via RegEx. A few days ago I found a paper on the web, which describes a [Shallow XML Parser via regex](https://www2.cs.sfu.ca/~cameron/REX.html). Maybe that is of interest to you. – amix Oct 07 '20 at 01:39

1 Answers1

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);
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27