2011-04-29 64 views
0

是否有直接將元素對象轉換爲HTMLOption對象的方法? 讓我們假設我有這樣的XML:將XML選項元素節點轉換爲HTML選項標籤

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

我想插入每個選項在此選擇

有沒有辦法,只是直接將這些XML來選擇或我要,然後瀏覽XML,然後獲取我需要的所有信息,然後創建一個新選項並將該選項添加到選擇中? 類似:

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

爲本地代碼將是很好的^^ 注:我不想使用任何庫或框架。我想要自己學習並做到這一點。

回答

1

XSLT用於XML到HTML的轉換。像這樣的事情將做的伎倆:

<?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>