1

这个问题涉及

XSLT 生成 XML 中指定的 html 标记

我有一个xml文档并使用xsl生成html标签

<xsl:element name="{Type}" >

我遇到的问题是我想在我的 xml 中指定一些 html 属性,例如

<Page>
  <ID>Site</ID>
  <Object>
    <ID>PostCode</ID>
    <Type>div</Type>
    <Attributes>
       <Attribute name="class">TestStyle</Attribute>
       <Attribute name="id">TestDiv</Attribute>
    </Attributes>
    <Class>display-label</Class>
    <Value>PostCode</Value>
  </Object>
</Page>

那么有谁知道我如何使用 xsl 用两个属性填充 xsl:element ?

谢谢

4

3 回答 3

4

从我在上一个问题中发布的样式表构建,在元素声明中,您可以遍历每个Attributes/Attribute元素并为您正在构建的元素构造属性。

您“站在”Object该 for 循环内的元素节点上,因此您可以像这样迭代它的Attributes/Attribute元素:

<xsl:for-each select="Attributes/Attribute">
  <xsl:attribute name="{@name}"><xsl:value-of select="current()"/></xsl:attribute>
</xsl:for-each>

应用于您的样式表:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:output method="html" indent="yes"/>
  <xsl:template match="/">
    <html>
      <head>
      </head>
      <body>
        <xsl:for-each select="Page/Object">
            <xsl:element name="{Type}" >
                <xsl:for-each select="Attributes/Attribute">
                    <xsl:attribute name="{@name}"><xsl:value-of select="current()"/></xsl:attribute>
                </xsl:for-each>
                <xsl:value-of select="Value"/>
            </xsl:element>
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

这是实现相同输出的另一种方法,但以一种更夸张的方式,使用apply-templates代替for-each.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:output method="html" indent="yes"/>
  <xsl:template match="/">
    <html>
      <head>
      </head>
      <body>
        <xsl:apply-templates select="Page/Object" />
      </body>
    </html>
  </xsl:template>

  <xsl:template match="Object">
    <xsl:element name="{Type}" >
       <xsl:apply-templates select="Attributes/Attribute" />
       <xsl:apply-templates select="Value" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="Attribute">
     <xsl:attribute name="{@name}"><xsl:value-of select="."/></xsl:attribute>
  </xsl:template>

</xsl:stylesheet>
于 2010-01-18T17:00:53.473 回答
2

您需要修复Attributes源示例中的元素,它没有关闭。

您可以使用xsl:for-eachor xsl:apply-templateswith select="Attributes/Attribute", 来调用xsl:attribute看起来有点像这样的元素:

<xsl:attribute name="{@name}"><xsl:value-of select="text()"/></xsl:attribute>

您需要注意的是,它xsl:attribute必须出现在任何将子元素添加到{Type}元素之前。

于 2010-01-18T16:46:36.053 回答
1
<xsl:element name="Attribute">
  <xsl:attribute name="class">TestStyle</xsl:attribute>
  <xsl:attribute name="id">TestDiv</xsl:attribute>
</xsl:element>
于 2010-01-18T16:26:56.687 回答