Matching an XPath expression against a javascript variable

987 views Asked by At

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.

1

There are 1 answers

0
t0mppa On BEST ANSWER

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);