2013-12-12 54 views
1

我有以下XML节点:XSL for循环节点模式

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

我要循环通过与文本格式[数字]文本名称的每个节点。 所以我做:

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

但没有奏效。

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

回答

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 
+0

当部署它告诉我: ERROR: '' Sintax错误 '根/父/ * [开始-与(./名称(),' 节点“)] – Wolfchamane

+0

它适用于XSLT 2.0和Saxon 9.1。你与什么工作?另外,我没有写'starts-with(./ name(),'node')'。 –

+0

我知道,我知道 我正在使用1.0 它正确部署与“[开始(名称(),'孩子')]”“,但没有节点检索,我测试了它与计数() – Wolfchamane

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> 

我认为,结构更清晰,只是不同的充方式。

问候

+0

谢谢,但我无法更改XML结构。 – Wolfchamane