How to filter an XML variable with Javascript

Based on the following object:

var xmlData =  `<?xml version="1.0" encoding="UTF-8"?> <log>   <entry id="1">     <message>Application started</message>   </entry>   <entry id="2">     <message>Application ended</message>   </entry>   <entry id="3">     <message>Application ended</message>   </entry> </log>` 

I would need to retrieve the id’s of those nodes that are repeated. For example, if you check this out, you’ll realize that there are two nodes, called "message", that have the same text: "Application ended".

So I would need to return those two id’s (2 & 3).

I’ve been doing this so far:

function getId(xml, message) {   parser = new DOMParser();   xml = parser.parseFromString(xmlData,"text/xml");      for (var i = 0; i < xml.getElementsByTagName("entry").length; i++){        } } 

As you can see, I’ve created a function, I parsed the xml and turned into a DOM document, and now I need to filter it only to return those two entries. So far, I’ve reached the part where I can check inside those nodes, but now I can not think of a good way to filter them.

Any ideas?

Thanks in advance.

Add Comment
1 Answer(s)

Supposing your XML keeps the same structure, we can write this :

function getId(xml, message) {       var parser = new DOMParser();       xml = parser.parseFromString(xmlData,"text/xml");       var ids = [];              for (var i = 0; i < xml.getElementsByTagName("entry").length; i++){            var msg = xml.getElementsByTagName("entry")[i].childNodes[0].nextSibling.innerHTML;                if(msg == message)              ids.push(xml.getElementsByTagName("entry")[i].id);       }              return ids;     }           var ids = getId(xmlData,"Application ended");     console.log(ids) // returns ["2", "3"]      

the line var msg = xml.getElementsByTagName("entry")[i].childNodes[0].nextSibling.innerHTML; is looking up the nextSibling (the tag in your XML) but if your structure changes, you’ll have to get all the nodes and check for the one named "message".

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.