XSL for循环节点模式

时间:2013-12-12 09:06:28

标签: xml regex xslt

我有以下XML节点:

<parent>
   <child1name>value</child1name>
   <child2name>value</child2name>
   <child3name>value</child3name>
   <child4name>value</child4name>
   <others />
</parent>

我想循环遍历每个节点,其名称格式为text [digit]文本。 所以我做了:

<xsl:for-each select="parent/child*name">
   Value <xsl:value-of select="position()" />: <xsl:value-of select="." />
</xsl:for-each>

但它不起作用。

什么是正确的模式?可能"child\d{1}name"

2 个答案:

答案 0 :(得分:1)

正确的模式是

<xsl:for-each select="parent/*[starts-with(./name(),'child')]">

否则,如果您需要更严格的限制:

<xsl:for-each select="parent/*[starts-with(./name(),'child') and ends-with(./name(),'name')]">

此外,将文本合并到这样的样式表中并不是一个好习惯。相反,您可以在xsl:text元素中包含任何文本。

使用您显示的输入代码段的整个样式表:

<?xml version="1.0" encoding="utf-8"?>

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

<xsl:output method="text"/>

<xsl:template match="/">
  <xsl:for-each select="parent/*[starts-with(./name(),'child') and ends-with(./name(),'name')]">
  <xsl:text>Value </xsl:text>
  <xsl:value-of select="position()" />
  <xsl:text>: </xsl:text>
  <xsl:value-of select="." />
  <xsl:text>&#10;</xsl:text>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

这给出了以下输出:

Value 1: value
Value 2: value
Value 3: value
Value 4: value

答案 1 :(得分:0)

我会改变XML结构。对我来说,更容易在没有模式的情况下运行子元素:

<parent>
  <childs>
    <child>
      <id>1</id>
      <name>value</name>
    </child>
    <child>
      <id>2</id>
  <name>value</name>
    </child>
    <child>
      <id>3</id>
  <name>value</name>
    </child>
    <child>
      <id>4</id>
  <name>value</name>
    </child>
   </childs>
   <others />
 </parent>

我认为结构更清晰,只是一种不同的方法。

问候