2

I have XML content that I need to query from within javascript. To use a simple example, here is the XML:

<books>
  <book>
    <title>ABC</title>
    <author>Smith, John</author>
    <subject>Science Fiction</subject>
  </book>
  <book>
    <title>DEF</title>
    <author>Jones, Tom</author>
    <subject>Biography</subject>
  </book>
</books>

This XML is referenced in an 'xmlDoc' variable.

Now I want to find all nodes where the child node is equal to a value passed in via a URL parameter, or some other dynamically selected method. This category is stored in a variable called 'category'.

I can create an evaluate expression like:

var result = xmlDoc.evaluate('/books/book[category="Biography"]', xmlDoc, null, XPathResult. ANY_TYPE,null);

if I statically enter the category value.

But how do I check if the value of the node matches the value of the 'category' variable? I likely need to escape the 'category' variable in some way, but I cannot figure it out.

Mark Salamon
  • 569
  • 1
  • 8
  • 21
  • 1
    Am I missing something or why would you not just use `'/books/book[category="' + category + '"]'`? – t0mppa Nov 21 '14 at 20:10
  • you're not missing anything. But apparently I am, my brain. :) Sorry, I was looking for something more complex when the answer was straightforward. thanks! – Mark Salamon Nov 21 '14 at 20:15
  • @t0mppa you should add that as an answer so it can be accepted. –  Nov 21 '14 at 20:22
  • 1
    @LegoStormtroopr: Added, it just seemed like a too simple question and thus would have a catch. :) – t0mppa Nov 21 '14 at 20:35

1 Answers1

3

Just as you would concatenate Strings normally in JavaScript. That is by using the + operation:

var result = xmlDoc.evaluate('/books/book[category="' + category + '"]',
                             xmlDoc, null, XPathResult.ANY_TYPE, null);
t0mppa
  • 3,983
  • 5
  • 37
  • 48