Billy said:
How do you go about populating a select list from an XML file?
I can open the XML file fine and get at all of the data, but I'm stuck on
how to use that data in my <option> tags. Is it even possible?
It depends on the browser how you do it, or how you finally do it
depends on what browsers you target.
If you look at Mozilla or at Opera 8 which have their own combined XML
and HTML DOM implementation then you simply need to make sure you put
XHTML <option> elements in the XML by using the proper namespace and
then you can use the importNode method to import the nodes from the XML
DOM document into your HTML document and use appendChild to insert the
elements into the <select>, e.g.
// parsing X(HT)ML from string here for the example
// but could of course load/parse from a URL
var xmlDocument = new DOMParser().parseFromString(
[
'<dt:data xmlns:dt="
http://example.com/2005/dt"',
' xmlns="
http://www.w3.org/1999/xhtml">',
'<option>Kibo</option>',
'<option>Xibo</option>',
'<option>Jaffo</option>',
'</dt:data>'
].join('\r\n'),
'application/xml'
);
var select = document.createElement('select');
var options = xmlDocument.getElementsByTagNameNS(
'
http://www.w3.org/1999/xhtml',
'option'
);
for (var i = 0; i < options.length; i++) {
select.appendChild(
select.ownerDocument.importNode(options
, true));
}
document.body.appendChild(select);
With IE the problem is that IE itself implements the HTML DOM and the
XML DOM is implemented by MSXML and script simply uses MSXML as an
ActiveX component, there is no importNode to move nodes from one DOM
implementation to the other, and even if you use the proper XHTML
namespace then in MSXML's XML DOM you simply have some Element nodes but
not HTMLElement or HTMLOptionElement nodes. So with IE you would need to
write some importNode yourself which traverses the XML DOM and creates
the necessary HTML DOM nodes or you could consider to treat the input as
a markup string which you assign the innerHTML of the select. But the
latter does strange things here for me with IE 6 on Windows XP SP 2, it
does not look like setting innerHTML on the select is a working approach
to get any options to show up.