ilinsky / jquery-xpath

jQuery XPath plugin (with full XPath 2.0 language support)
180 stars 64 forks source link

Element names in XPath don't match anything, but predicate filters do #8

Closed CoDEmanX closed 9 years ago

CoDEmanX commented 10 years ago

I'm loading an XML file via File Reader API (local only), parse it as text, let jQuery turn it into a DOM tree and append it to the page. Then I wanna run xpath queries on this DOM tree.

The problem: an empty object is returned whenever I try to use element names in the xpath expression

// Doesn't work, empty object
$(document.body).xpath("//div[1]/node()[3]/sourceFile")

Whereas a * (to match all immediate children) combined with a predicate filter using the node name works

// Returns sourceFile node, [0].innerHTML gets the text
$(document.body).xpath("//div[1]/node()[3]/*[name()='sourceFile']")

Am I overlooking something obvious, or is this a bug in jquery-xpath?

It definately considers the dynamically added document nodes when using a predicate filter, so I see no reason why it wouldn't work for a direct XPath.

http://jsfiddle.net/sHz8k/

Example XPath using a predicate filter that works: //*[name()='sourceFile'] Direct XPath that does not work: //sourceFile

Test xml:

<?xml version="1.0" encoding="UTF-8"?>
<conversion>
  <server/>
  <sourceFile>CEN_140107.mdb</sourceFile>
  <dataSourceType>MSAccess</dataSourceType>
  <output>
    <table>filmwerk</table>
    <format>UTF8</format>
  </output>
</conversion>

Check the console to inspect the object $.xpath() returns.

ilinsky commented 9 years ago

The problem has to do with namespaces. The HTML page elements have XHTML namespace and this is the namespace to which evaluator defaults all non-prefixed element selectors to. When you render an XML document with jQuery there is chance these elements now have namespace set to null. So, either you need to supply namespace resolver with the query or change XML embedding mechanism into HTML