0

Is there a direct was to convert an Element Object to an HTMLOption Object? Let's suppose I have this XML:

<?xml version='1.0'?>
    <options>
        <option value="1">Hello1</option>
        <option value="2">Hello2</option>
    </options>

I want to insert each option in this select

Is there a way to just convert these XML to option directly or I have to then navigate the XML then get all information I need and then create a new Option and add that option to the select? something like:

var options = XmlCode.getElementsByTagName('option');
for(var i = 0; i < options.length; i++){
    selectBox.add(options[i]);
}

as a native code would be nice ^^ Note: I don't want to use any libraries or frameworks. I want do learn and do this by myself.

4

1 回答 1

1

XSLT is made for XML to HTML conversion. Something like this will do the trick:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="select2option.xml" ?>
<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:html="http://www.w3.org/1999/xhtml"
            >

<xsl:output method="html" encoding="utf-8" indent="yes" standalone="yes" media-type="text/html" omit-xml-declaration="yes" doctype-system="about:legacy-compat" />

<html:options>
  <html:option name="foo">bar</html:option>
</html:options>

<xsl:template match="xsl:stylesheet">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="/">
 <html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  </head>
  <body>
    <xsl:apply-templates/>
  </body>
 </html>
</xsl:template>

<xsl:template match="html:options">
 <select>
  <xsl:apply-templates />
 </select>
</xsl:template>

<xsl:template match="html:option">
 <option name="@name">
  <xsl:apply-templates />
 </option>
</xsl:template>
</xsl:stylesheet>
于 2012-04-25T06:36:51.040 回答