0

I've looked through this entire site as various ways in searching through an XML file using a value taken from a html input field and have managed to do this, however when it finds the match thats all I can do is display a message saying "Match Found!".

What I'd like to do is be able to search the XML file using the search string value put into the html input field, then once its found a match pull the rest of the information for that specific node - as in all the attributes.

Example of my XML file:

<dvdcatalogue>
<dvd year="1979" rating="18" director="ridley scott">Alien</dvd>
</dvdcatalogue>

The title of the film being "Alien" so that would be the search string.

Any ideas how this could be done? I'm guessing it has something to do with loading into a javascript array maybe. Just to make anyone who answers aware none of the examples I've seen thus far have been that clear on the exact code that would achieve this.

Thanks in advance for the help!!

GeordieDave1980
  • 589
  • 4
  • 11
  • 25
  • Have a look at [XML Path Language](http://www.w3.org/TR/xpath/) for your question. And at [Cross-browser XPath implementation](http://stackoverflow.com/questions/183369/cross-browser-xpath-implementation-in-javascript) for the actual implementation – Andreas May 02 '12 at 07:58
  • Had a look but that stuff is kinda outta my league at the moment. Surely there is a javascript function that can do it using FOR loops and arrays? I'm probably going wrong somewhere with my own code. – GeordieDave1980 May 02 '12 at 18:25

1 Answers1

0

You could use jQuery for this task as well, like I've done it in this fiddle (although XPath would be the more correct way of doing it^^)

var xml = $("<dvdcatalogue>" +
               "<dvd year=\"1979\" rating=\"18\" director=\"ridley scott\">Alien</dvd>" +
               "<dvd year=\"1986\" rating=\"18\" director=\"ridley scott\">Aliens (aka. Alien 2)</dvd>" +
               "<dvd year=\"1984\" rating=\"18\" director=\"James Cameron\">Terminator</dvd>" +
               "</dvdcatalogue>"),
       search = "Alien",
       result = $("#result"),
       nodes;

       nodes = xml.find("dvd:contains('" + search + "')");

    if (nodes.length > 0) {
        nodes.each(function(i, e) {
            result.append("<li><b>" + e.firstChild.nodeValue + "</b> by " + e.getAttribute("director") + "</li>");
        });
    }
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • Thanks for the input on that. Unfortunately it is in javascript rather than jquery that I need to do it. I have looked at XPath through the W3C schools site but its not fully clear on what xpath does nor does it provide any decent examples of how it works and how you use it in Javascript. Any ideas? – GeordieDave1980 May 04 '12 at 22:45