1

I want to get OBS_VALUE value of Obs tag that has 2017-Q4 as TIME_PERIOD value.

Here's a sample of the xml file I have :

XML

<Obs TIME_PERIOD="2018-Q1" OBS_VALUE="547289" OBS_STATUS="A" OBS_QUAL="DEF" OBS_TYPE="A"/>
<Obs TIME_PERIOD="2017-Q4" OBS_VALUE="545905" OBS_STATUS="A" OBS_QUAL="DEF" OBS_TYPE="A"/>
<Obs TIME_PERIOD="2017-Q3" OBS_VALUE="542169" OBS_STATUS="A" OBS_QUAL="DEF" OBS_TYPE="A"/>

Here's what I already achieve (it's working)

JS

var x = Dataval.getElementsByTagName('Obs')[1].getAttributeNode("OBS_VALUE");

But I want to select tag the other way : by it's TIME_PERIOD value.

Renaud
  • 57
  • 1
  • 6
  • Possible duplicate of [Is there a way to getElement xml by attribute?](https://stackoverflow.com/questions/7083341/is-there-a-way-to-getelement-xml-by-attribute) – Heretic Monkey Oct 01 '19 at 19:49
  • Or [Find xml attribute values with javascript](https://stackoverflow.com/q/11624448/215552) – Heretic Monkey Oct 01 '19 at 19:51

1 Answers1

0

with jquery you can select from a set of elements the one which has a certain attribute this way:

var tp="2017-Q4"
var x=$('Obs[TIME_PERIOD="'+tp+'"]').attr('OBS_VALUE')
console.log(x)

which outputs in the console: 545905

with vanilla javascript you can achieve the same with:

var tp="2017-Q4"
var obs = document.getElementsByTagName('Obs');

for (ob of obs) {
  t_p = ob.getAttribute('TIME_PERIOD');
  if (t_p === tp) {
    // output data 
    console.log(ob.getAttribute('OBS_VALUE'))
  }
}

var tp = "2017-Q4"
var x = $('Obs[TIME_PERIOD="' + tp + '"]').attr('OBS_VALUE')


console.log('jquery: '+x)


var obs = document.getElementsByTagName('Obs');

for (ob of obs) {
  t_p = ob.getAttribute('TIME_PERIOD');
  if (t_p === tp) {
    // Grab the data 
    console.log('javascript: '+ob.getAttribute('OBS_VALUE'))
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<Obs TIME_PERIOD="2018-Q1" OBS_VALUE="547289" OBS_STATUS="A" OBS_QUAL="DEF" OBS_TYPE="A" />
<Obs TIME_PERIOD="2017-Q4" OBS_VALUE="545905" OBS_STATUS="A" OBS_QUAL="DEF" OBS_TYPE="A" />
<Obs TIME_PERIOD="2017-Q3" OBS_VALUE="542169" OBS_STATUS="A" OBS_QUAL="DEF" OBS_TYPE="A" />
Vickel
  • 7,879
  • 6
  • 35
  • 56