Search code examples
xmlmsxmlxpath

MSXML string-compare problem


Can someone please explain why this JavaScript code outputs zero instead of one? Also, when elements //e[2] and //e[3] are swapped then it works, why?

doc = new ActiveXObject("MSXML2.DOMDocument.4.0");
doc.loadXML(
"<r>               " +
"   <e id='a'>     " +
"      <e id='b'/> " +
"      <e id='c'/> " +
"   </e>           " +
"</r>              ")
doc.setProperty("SelectionNamespaces", "xmlns:ms='urn:schemas-microsoft-com:xslt'");
WScript.Echo(doc.selectNodes("/r/e[ms:string-compare(e/@id,'c','en-US', 'i')=0]/@id").length);

Solution

  • Can someone please explain why this JavaScript code outputs zero instead of one? Also, when elements //e[2] and //e[3] are swapped then it works, why?

    Because the firm of your extension function is

    number ms:string-compare(string x, string y, [,string language _
                                                 [,string options]])
    

    So, the e/@id inner most expression evaluated to a node set is cast to string taking the first node in the node set.

    Without extension, you could use:

    /r/e[e/@id[translate(.,'C','c')='c']]/@id"