如何使用XSL将XML属性值分配给下拉列表

时间:2010-06-01 05:28:02

标签: asp.net xml xslt c#-2.0

我有一个样本xml;

<?xml version="1.0" encoding="iso-8859-9"?>
    <DropDownControl id="dd1" name="ShowValues" choices="choice1,choice2,choice3,choice4">
</DropDownControl >


我需要使用XSL创建此XML的UI表示。我想用SELECT属性中指定的值填充下拉列表。
有没有人对此有任何想法?
在此先感谢:)

1 个答案:

答案 0 :(得分:0)

如果您搜索了StackOverflow,您会发现有许多与字符串分割有关的问题。

这是一个,例如:

Comma Separated String Parsing

在你的情况下,在这里你将如何使用它

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="/DropDownControl">
      <select>
         <xsl:call-template name="split">
            <xsl:with-param name="list" select="@choices"/>
         </xsl:call-template>
      </select>
   </xsl:template>

   <xsl:template name="split">
      <xsl:param name="list" select="''"/>
      <xsl:param name="separator" select="','"/>
      <xsl:if test="not($list = '' or $separator = '')">
         <xsl:variable name="head" select="substring-before(concat($list, $separator), $separator)"/>
         <xsl:variable name="tail" select="substring-after($list, $separator)"/>
         <option>
            <xsl:value-of select="$head"/>
         </option>
         <xsl:call-template name="split">
            <xsl:with-param name="list" select="$tail"/>
            <xsl:with-param name="separator" select="$separator"/>
         </xsl:call-template>
      </xsl:if>
   </xsl:template>

</xsl:stylesheet>

这将生成以下XML / HTML

<select>
<option>choice1</option>
<option>choice2</option>
<option>choice3</option>
<option>choice4</option>
</select>

如果您能够使用XSLT2.0,则可以使用tokenise函数。请参阅此页面以获取示例

Best way to split and render comma separated text as html

但是,我注意到你被标记为asp.net和c#2.0这个问题,这表明你无法直接使用XSLT2.0。

另一种可选方案是,假设使用C#进行转换,则在转换完成之前,您将在后面的代码中进行拆分。编写一些代码来读取XML,访问属性,使用.Net的字符串拆分函数,并将子元素附加到DropDownControl元素。