Let's say you're a developer and you're working on the latest disruptive app. This app tells you the property value of elderly homes in your area. Really cutting edge stuff. Let's say you're relying on the zillow API for your property data. There's just one problem with this API: It returns, GASP, XML!

Welcome to the real world.

As a rock star developer, you've never dealt with XML APIs. "Wait, this isn't JSON API spec compliant?" you ask yourself in disbelief. No friend, this is the real world. In the real world, nobody cares about you. Nobody holds your hand and tells you everything will be alright. Nobody is going to pay your bills, make your coffee, rock you to sleep and tell you you're the prettiest developer in the whole school.

Where was I? Oh right, XML APIs.

Enter DOMParser

DOMParser is an amazing class in javascript. DOMParser can parse an HTML or XML string and create a new HTML document from it. Essentially, you can parse an XML string, and use all your favorite DOM functions to iterate over objects. It's unbelievable! Let's go over an example.

Lets say you have this XML string from an API response:


1220 Hillside Rd
Fairfield, CT, 06824
Request successfully processed058784207https://www.zillow.com/homedetails/1220-Hillside-Rd-Fairfield-CT-06824/58784207_zpid/http://www.zillow.com/homedetails/1220-Hillside-Rd-Fairfield-CT-06824/58784207_zpid/#charts-and-datahttp://www.zillow.com/homes/58784207_zpid/http://www.zillow.com/homes/comps/58784207_zpid/
1220 Hillside Rd06824FairfieldCT41.17575-73.288364
174956011/07/2017-37584166208218370380536,800http://www.zillow.com/local-info/CT-Fairfield/r_31506/http://www.zillow.com/fairfield-ct/fsbo/http://www.zillow.com/fairfield-ct/

How in the world can you parse this?

Let's take this xml string and parse it into a DOM document! Then we can fetch the zpid of this property.


let request = new Request(`https://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1bt28y9dgcr_7galu&citystatezip=${someCityStateAndZip}&address=${someAddress}`);

fetch(request).then((results) => {
  // results returns XML. lets cast this to a string, then create
  // a new DOM object out of it!
  results
    .text()
    .then(( str ) => {
      let responseDoc = new DOMParser().parseFromString(str, 'application/xml');
      return responseDoc.getElementsByTagName('zpid')[0].textContent;
    }
  });

This will return the ZPID of the property we were looking up through the zillow API!

Breaking it down

  1. Get an XML response from the API
  2. use new DOMParser.parseFromString(string, "application/xml") to parse result
  3. use any document function to parse for the data you want
  4. YAY!

I find that javascript has an awesome built in solution to handling XML. Parsing an XML string into a DOM tree just feels right, and is very intuitive.