开发者

Parse DOM in XPCOM autocomplete component

开发者 https://www.devze.com 2023-04-03 06:49 出处:网络
I know we should use JSON when receiving remote \"autocomplete suggestions\", but I\'m forced to use standard DOM valid XHTML

I know we should use JSON when receiving remote "autocomplete suggestions", but I'm forced to use standard DOM valid XHTML

I have registered component of interface nsIAutoCompleteSearch and using this code, to get remote XHTML via XmlHttpRequest

var request = Components.classes["@mozilla.org/xmlextras/xmlhttpreque开发者_如何转开发st;1"]
        .createInstance(Components.interfaces.nsIXMLHttpRequest);

so far OK. then I receive text from request.responseText and I need to parse DOM and get values, too overcomplicated with regexp

so here is a code with error:

Components.classes["@mozilla.org/feed-unescapehtml;1"]
                    .getService(Components.interfaces.nsIScriptableUnescapeHTML)
                    .parseFragment(request.responseText, false, null, document);

error saying document not defined. Because I'm in XPCOM component, I don't have access to DOM of page or XUL overlays. This code is taken right from MDN Docs

I tried to create instance of nsIDOMDocument or nsIDOMHTMLDocument and loading them from @mozilla.org/dom/core;1 or @mozilla.org/dom/html;1, but these packages doesn't seem to be accessible (error saying Components.classes['@mozilla.org/dom/core;1'] is undefined)

So Is there a way how to create new DOMDocument, insert request.responseText as HTML and then walk through its DOM structure?

function HTMLParser from given link is throwing same error about document not defined

Thanks


If the server response is well-formed XHTML, you can just use the responseXML member of the request object.

This only works if the server is returning content type text/xml, however. Otherwise you can force the MIME type to text/xml using XMLHttpRequest.overrideMimeType.

A final possibility is to parse the document manually as in the original question. I would use DOMParser though. You can use it from an XPCOM component like this:

var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  createInstance(Ci.nsIDOMParser);  
var doc = parser.parseFromString(aStr, "text/xml");
0

精彩评论

暂无评论...
验证码 换一张
取 消