2

我是XSL的新手。我正在尝试使用 XSL 文件读取 XML 元素的值。我的 XML 文件是这样的:

<PersonList>
  <Person>
    <Name>person1</Name>
    <Age>21</Age>
  </Person>
  <Person>
    <Name>person2</Name>
    <Age>21</Age>
  </Person>
</PersonList>

我的 XSL 文件如下:

<xsl:stylesheet version="1.0" xmlns=...>
  <xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml declaration="no" />
  <xsl template match="/">
    <PersonList>
      <xsl:for-each select="PersonList/Person">
        <Person>
          <xsl:for-each select="*">
            <xsl:variable name="elementName">
              <xsl:value-of select="name(.)" />
            </xsl:variable>
            <xsl:variable name="elementValue">
              ???
            </xsl:variable>
          </xsl:for-each>
        </Person>
      </xsl:for-each>
    </PersonList> 
  </xsl:template>
</xsl:stylesheet>

我应该如何替换???以获取存储在elementName变量中的元素的值。我分别尝试了以下三行:

<xsl:value-of select="value(.)" /> 
<xsl:value-of select="value($elementName)" />
<xsl:value-of select="$elementName" />

但没有运气。请帮忙!

4

2 回答 2

3

??????????????????可以是<xsl:value-of select="."/>(即上下文元素的字符串值。)它与$elementName.

你可以像这样更简洁地做到这一点:

<xsl:for-each select="*">
  <xsl:variable name="elementName" select="name()"/>
  <xsl:variable name="elementValue" select="string(.)"/>
</xsl:for-each>

但是你的模板真的很奇怪。您正在收集这些变量,但您没有对它们做任何事情——它们不会出现在输出中。你想得到什么输出?

使用for-each通常是代码气味。在几乎所有情况下,您最好使用多个模板:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="no" />

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Person/*">
    <xsl:variable name="elementName" select="name()"/>
    <xsl:variable name="elementValue" select="string(.)"/>
</xsl:template>

</xsl:stylesheet>

这种复制几乎所有内容并只更改一点点 xml 的模式非常常见且非常强大,您应该学习如何使用它

于 2013-04-15T18:34:34.337 回答
0

好吧,如果您真的想获取名称保存在变量中的元素的值,那么在您的情况下,您可以这样做

<xsl:variable name="elementValue">
    <xsl:value-of select="../*[name()=$elementName]" />
</xsl:variable>

但是,这是非常复杂的事情。您处于xsl:for-each循环中,遍历Person的子元素。因此,因为您已经定位在您想要其值的元素上,您可以这样做而忘记elementName变量。

<xsl:variable name="elementValue">
    <xsl:value-of select="."/>
</xsl:variable>

实际上,您可以将循环简化为

<xsl:for-each select="PersonList/Person">
   <Person>
      <xsl:for-each select="*">
         <xsl:value-of select="." />
      </xsl:for-each>
   </Person>
</xsl:for-each>
于 2013-04-15T18:31:06.147 回答