Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active March 27, 2017 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dogrunjp/afc2abd27bf808eb0028e332dd850fc4 to your computer and use it in GitHub Desktop.
Save dogrunjp/afc2abd27bf808eb0028e332dd850fc4 to your computer and use it in GitHub Desktop.
XML parsing from SPARQL endpoint with javascript ES6

XML parsing from SPARQL endpoint with javascript ES6

NodeList has no map method, forEach method, so it's boring to parsing xml type dataset in js.

if Chrome...

if Chrome forEach method is OK

elements = xmlRoot.querySelectorAll('result');
elements.forEach(function(x){
    var items = x.getElementsByTagName('binding')[0].getAttribute('name');
    console.log(items)
});

and (for .. of) is OK too.

elements = xmlRoot.querySelectorAll('result');
for(let x of elements){
    let items = x.getElementsByTagName('binding')[0].getAttribute('name');
    console.log(items)
}

Array.prototype.forEach.call

this method is OK with Chrome and safari.

Array.prototype.forEach.call(xmlRoot.querySelectorAll('result'), function(x){console.log(x.getElementsByTagName('binding'))});

it's seems better to use arrow function as callback, but safari does not corresponde to this method.

Array.from

this ES6 method is OK with Chrome and safari too.

items = Array.from(xmlRoot.querySelectorAll('result'), function(x){return  x.getElementsByTagName('binding')});
console.log(items)

ES6 xml parser sample for SPARQL endpoint

// 選択した遺伝子のgene idでrefexの情報を取得
function get_refex_info(gid){
    var qs = encodeURIComponent(query_refex_info(gid));
    var q = endpoint + "?query=" + qs;
    d3.xml(q, function (error, xmlRoot) {
        items = Array.from(xmlRoot.querySelectorAll('result'), function(x){return x2obj(x)});
        console.log(items[0])
    })
}

// NodeListをオブジェクトに変換
function x2obj(x) {
    var item = {};
    item['refex'] =  x.querySelectorAll('[name=refex]').item(0).textContent;
    item['sample'] = x.querySelectorAll('[name=sample]').item(0).textContent;
    item['organism'] = x.querySelectorAll('[name=organism]').item(0).textContent;
    item['exp_val'] = x.querySelectorAll('[name=expression_value]').item(0).textContent;
    item['sample_cat'] = x.querySelectorAll('[name=sample_category]').item(0).textContent;
    return item
}

reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment