使用xslt从属性中获取值

时间:2012-07-09 11:31:47

标签: xml xslt xpath

input.xml中:

<comp>
  <link id="#c1-tbl-0001"/>
</comp>

的Output.xml:

<comp>
  <link newid="#c1-tbl-0001"/><tableno>1.1</tableno>
</comp>

我需要来自属性值的tableno的值,如来自tb1的1和来自0001的另一个1,因此输出应为1.1

我使用了以下xsl,但它没有给出确切的结果。

 <xsl:element name ="tableno">
  <xsl:value-of select ="substring(@id,7)"/>.<xsl:value-of select="substring(@id,12)"/>
</xsl:element>

3 个答案:

答案 0 :(得分:0)

首先,您要阅读的属性名为id,而不是href。 (编辑:你好像纠正了这个。)

您必须为第一个substring电话提供一个长度,以便它只捕获一个数字:

<xsl:value-of select="substring(@id, 7, 1)"/>.<xsl:value-of select="substring(@id, 12)"/>

如果第二个数字可能使用多个数字,但您想要删除零,则可以执行

<xsl:value-of select="substring(@id, 7, 1)"/>.<xsl:value-of select="number(substring(@id, 9))"/>

答案 1 :(得分:0)

输入中有错误。看起来你在“tbl”中有一个字母l,你打算把数字1放在“tb1”中。

无论如何,这是你如何做到的......

如果输入文件是......

<comp>
  <link id="#c1-tbl-0001"/>
</comp>

...然后应用样式表...

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

<xsl:template match="/comp">
<comp>
  <link newid="#c1-tbl-0001"/>
  <tableno><xsl:value-of select="concat( substring(link/@id,7,1), '.')" />
           <xsl:number value="substring(link/@id,9)" /></tableno>
</comp>
</xsl:template>

</xsl:stylesheet>

......会产生......

<?xml version="1.0" encoding="utf-8"?>
<comp>
  <link newid="#c1-tbl-0001" />
  <tableno>1.1</tableno>
</comp>  

备用模板内容可能是......

<comp>
  <link newid="#c1-tbl-0001"/>
  <tableno><xsl:value-of select="
   concat( substring(link/@id,7,1), '.', number( substring(link/@id,9))" />
  </tableno>
</comp>

使用效果更好,因为您可以很好地控制格式化。

答案 2 :(得分:0)

更通用的解决方案,以防我们只知道有两个数字由包含短划线的字符串分隔:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="link">
     <xsl:value-of select=
     "translate(concat(substring-before(@id, '-'),
                     '.',
                        substring-after(@id, '-')
                     ),
                            translate(concat(substring-before(@id, '-'),
                                             '.',
                                             substring-after(@id, '-')
                                             ),
                                       '.123456789',
                                       ''
                                       ),
                      ''
                      )
     "/>
 </xsl:template>
</xsl:stylesheet>

在提供的XML文档上应用此转换时:

<comp>
    <link id="#c1-tbl-0001"/>
</comp>

产生了想要的正确结果:

1.1