1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

XML DOM Parser, 2-dimensional array problem

Discussion in 'JavaScript' started by iago111, Jul 18, 2020.

  1. #1
    Hello guys,

    I would like to put XML data in 2dim array and I don't get the job done.

    Everything is fine with the promise the loops are woking fine, but I don't get the 2nd dimension of the array done. (So I'm pretty 1-dimensional here).

    If s.b. would like to take a look at the code. Muchas gracias!

     (function(d) {
    
            let output = d.getElementById('output'); 
    
    
            getCurrentDate();
    
            d.addEventListener('DOMContentLoaded',()=> {
    
                //fetch data as soon as the page has loaded
    
                const proxyurl = "https://cors-anywhere.herokuapp.com/";
                let url = "http://www.xmltv.co.uk/feed/7365";
                fetch(proxyurl+url)
                .then(response => response.text())
                .then(data => {
    
                 //console.log(data); //string
                 let parser = new DOMParser();
                 let xml = parser.parseFromString(data,"application/xml");
                 //output.textContent = data;
                 console.log(xml);
    
                 channelList(xml);
                 //channelIdList(xml);
                
    
    
                });
               
            });
    
            function channelList(xml) {
    
                let tableFields = [[]];
               
                let list = d.getElementById('channelPrg');
    
                let channelName = xml.getElementsByTagName('display-name');
              //  let channelId = xml.getElementsByTagName('channel');  //for channel ID
    
              //  let programm = xml.getElementsByTagName('programme');    //for channel ID
                let title = xml.getElementsByTagName('title');
    
    
                for(let i=0; i < channelName.length; i++) {
                 
    
                     tableFields[i] = channelName[i].firstChild.nodeValue;
              
    
                    for(let j=0; j < title.length; j++) {
    
                      
                        if (channelName[i].parentNode.getAttribute("id") === title[j].parentNode.getAttribute("channel") ) {
    
                     
    
                            tableFields[i][j] = title[j].firstChild.nodeValue;
    
                        }
                    }
                }
    
                console.log(tableFields);
    
            }
         
    })(document);
    Code (JavaScript):
     
    iago111, Jul 18, 2020 IP
  2. iago111

    iago111 Member

    Messages:
    99
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    33
    #2
    Yeah, I don't get this array stuff in my brain:
    I changed the first loop like this:

      for(let i=0; i < channelName.length; i++) {
                
    
                  tableFields[i] = channelName[i].firstChild.nodeValue;
                  tableFields[i] = [];
    
    /// sendond loop {}
    
    }
    Code (JavaScript):
    Then I got this here: (only the entries of the second loop but not of the first one this time):

    upload_2020-7-20_10-37-37.png
     
    iago111, Jul 20, 2020 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #3
    I get the feeling you're overthinking this and using "for" loops when you should be walking the DOM... but the real killer is the fact that the data being input is NOT properly structured or organized, what with all the channels and programs being siblings to each-other instead of programs being children of each channel. When the source data is junk, of course it's hard to work with.

    Rather than an array, I'd suggest using an object or map where the ID's of the channels are your keys. Or even better, use cloneNode to build a new DOM fragment, since walking the DOM is faster than arrays, giving you the data in a format you want.

    Likewise I'd suggest getting rid of all the new-fangled promise and let/const crap. First off it's a bad idea due to legacy support (or lack therein) if this is client-side code, second it's REALLY not doing you any favors when it comes to error handling... much less you're in a perfectly good IIFE and none of your functions are long enough you should even be worrying about scope. It's all just pointless confusion and code bloat no matter how many "experts" are creaming their panties over these "features".

    And yes, those are "air quotes" as when I say "experts" and "features" I do so in extreme sarcasm!

    XMLHttpRequest would even be superior because "out of box" unless you override it doing so, it tries to create a XMLDom automatically for you. It's actually what it was designed to do, hence the XML in its name! This "fetch/then" crap is incompetent crippled nonsense, particularly when working with XML it's the same amount of code either way. (see XMLHttpRequest.responseXML)

    You should probably also be escaping your URI on the proxy so that you're not using invalid URI's.... and if you load your script right before </body> like a good little doobie, there's no reason to wait for DOMContentLoaded as you're pretty much already there.

    I think a more important questions is what are you trying to do with this array? What's the end goal? If you could do it straight on the XMLDomFragment instead of screwing around with arrays, do it.
     
    deathshadow, Jul 20, 2020 IP
  4. iago111

    iago111 Member

    Messages:
    99
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    33
    #4
    Now let's got back to year 1999 when we had activeX and IXMLHTTPRequest when people still believed that star treck was real.

    That's the code up to now, I mean I need the loops anyway!! Doesn't look really "sexy".

      (function(d) {
    
      const proxyurl = encodeURI("https://cors-anywhere.herokuapp.com/");
    
            let url = "http://www.xmltv.co.uk/feed/7365";
    
            let xhr = new XMLHttpRequest();
            xhr.open('GET',proxyurl+url,true);
    
            xhr.onreadystatechange = function() {
    
               // console.log(xhr.readyState);
                if(xhr.readyState == 4) {
    
                    switch(xhr.status){
    
                        case 200:
                        case 304:
                          console.log("Ok or not modified (cached)", xhr.status);
    
                          outputTV(xhr.responseXML);
                    }
    
                }
            };
    
            xhr.onerror = function(err) {
    
                console.warn(err);
            }
    
            xhr.send(null);
    
            function outputTV(str) {
    
                for(i=0; i<str.getElementsByTagName("display-name").length; i++) {
    
               console.log(str.getElementsByTagName("display-name")[i].firstChild.data);
              
    
                    }
    
            }
    })(document);
    Code (JavaScript):




     
    iago111, Jul 23, 2020 IP