xml - XSL使用其包含元素的位置更新属性

标签 xml xslt xpath

我正在尝试更新如下所示的文档:

 <document n="foo">
   <body>
      <seg xml:id="xkj">some text</seg>
      <seg xml:id="njk">some text</seg>
      <seg xml:id="ine">some text</seg>
      <seg xml:id="ocu">some text</seg>
   </body>
 </document>


这样,每个seg/@xml:id都会用文档中的document/@nseg/()position的串联进行更新。

结果将是:

 <document n="foo">
   <body>
      <seg xml:id="foo-1">some text</seg>
      <seg xml:id="foo-2">some text</seg>
      <seg xml:id="foo-3">some text</seg>
      <seg xml:id="foo-4">some text</seg>
   </body>
 </document>


我正在尝试的代码是:

<xsl:variable name="var_val" select="tei:document/n@"/>

<xsl:template match="tei:seg/@xml:id">
        <xsl:value-of select="'$var_val' || '-' || parent::node()/position()"/>
</xsl:template>


但是结果是,重复相同的position() = 1

 <document n="foo">
    <body>
      <seg xml:id="foo-1">some text</seg>
      <seg xml:id="foo-1">some text</seg>
      <seg xml:id="foo-1">some text</seg>
      <seg xml:id="foo-1">some text</seg>
    </body>
 </document>


我不是不了解position()还是没有正确地遍历XPATH轴。

提前致谢。

最佳答案

在与属性匹配的模板的上下文中,position()不是正确的工具,您需要count(../(., preceding-sibling::seg))或可以使用xsl:number

  <xsl:template match="seg/@xml:id">
      <xsl:variable name="pos" as="xs:integer">
          <xsl:number count="seg"/>
      </xsl:variable>
      <xsl:attribute name="{name()}" namespace="{namespace-uri()}" select="$var_val, $pos" separator="-"/>
  </xsl:template>


http://xsltfiddle.liberty-development.net/pPgCcok

关于xml - XSL使用其包含元素的位置更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045998/

相关文章:

java - 转换表单 2012,12,06,18,00,00 上的字符串以创建新的公历

xml - 如何在notepad++中使用正则表达式修剪xml标签中的空格?

xml - XSLT 和 xsl :for-each with a wildcard

asp.net - 使用 Entity Framework 在 asp.net mvc3 中的多个 xml 文档上运行 xpath 查询

sql-server - 抓取子级元素xml

perl - 将 XPath 与 Perl 一起使用

python - XML 走在 python 中

ios - Web 服务如何工作?

javascript - 火狐浏览器 : execute javascript in xslt

XSLT:XPath 上下文和文档()