【问题标题】:XSLT 2.0 - Converting array of elements to listXSLT 2.0 - 将元素数组转换为列表
【发布时间】:2013-12-18 17:31:14
【问题描述】:

学习XSLT,想知道这种转换是否可行

输入类似的内容

<book>
  <title>Title 1</title>
  <author>Author 1</author>
</book>
<book>
  <title>Title 2</title>
  <author>Author 2</author>
</book>
<book>
  <title>Title 3</title>
  <author>Author 3</author>
</book>

输出

<book1>
  <title1>Title 1</title1>
  <author1>Author 1</author1>
</book1>
<book2>
  <title2>Title 2</title2>
  <author2>Author 2</author2>
</book2>
<book3>
  <title3>Title 3</title3>
  <author3>Author 3</author3>
</book3>

XSLT 会是什么样子?

【问题讨论】:

  • 为什么不看看&lt;xsl:element&gt; 指令,它允许您创建一个具有计算名称的元素,并在 position() 函数中?
  • 这是可能的,但这可能是个坏主意——如果你有代表相同类型数据的元素,那么它们应该有相同的名称,你只是在为 XML 的下游消费者做更多的工作.

标签: xml xslt xpath xslt-2.0 xpath-2.0


【解决方案1】:

正如 cmets 中所述,这很容易,但不明智。但是,如果您承认这是不明智的,那么就没有理由说明如何。

首先,在 XSLT 中,有两种方法可以创建元素,将element inline:

<xsl:template match="book">
    <book1>
        <!-- Some stuff -->
    </book1>
<xsl:template>

或以编程方式使用xsl:element 指令:

<xsl:template match="book">
    <xsl:element name="book1">
        <!-- Some stuff -->
    </xsl:element>
<xsl:template>

如果我们使用attribute value template,上述代码中的@name 属性可以采用XPath 表达式。这意味着我们可以在其中插入一个动态值:

<xsl:template match="book">
    <xsl:element name="book{//some/xpath/here()}">
        <!-- Some stuff -->
    </xsl:element>
<xsl:template>

另外,我们可以使用position()Xpath函数根据当前上下文获取当前节点的位置

<xsl:template match="/">
    <xsl:for-each select="//book">
        <!-- this loop will number the books in the whole document 
             because its seaching in all nodes (//). -->
        <xsl:value-of select="position()"/>
    </xsl:for-each>
<xsl:template>

<xsl:template match="library">
    <xsl:for-each select=".//book">
        <!-- this loop will number the books in the current *library*
             because its seaching in all nodes under the library node (.//)  -->
        <xsl:value-of select="position()"/>
    </xsl:for-each>
<xsl:template>

正如 Michael Kay 在我输入这个 (grrr) 时在他的回答中所表明的那样,将这些结合起来是微不足道的。

【讨论】:

  • 谢谢。这很有意义。
【解决方案2】:

我不知道您为什么要创建如此糟糕的 XML 文档,但如果必须,您可以使用:

<xsl:template match="book">
  <xsl:variable name="n" select="position()"/>
  <xsl:element name="book{$n}">
    <xsl:element name="title{$n}">
      <xsl:value-of select="title"/>
    </xsl:element>
    <xsl:element name="author{$n}">
      <xsl:value-of select="author"/>
    </xsl:element>
  </xsl:element>
</xsl:template>

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 2014-07-29
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2019-11-02
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多