开发者

XSl Smart search and replace

开发者 https://www.devze.com 2023-01-20 12:52 出处:网络
Is it possible to do a find and replace to the attributes of a xml element?I want to change the directory that is开发者_如何学JAVA being pointed to by a href:

Is it possible to do a find and replace to the attributes of a xml element? I want to change the directory that is开发者_如何学JAVA being pointed to by a href:

From:

<image href="./views/screenshots/page1.png">

to

<image href="screenshots/page1.png"> 

And from:

<image href="./screenshots/page2.png">

to

<image href="screenshots/page2.png">

So by getting rid of all "./" that belong to the href of all image tags, but only the image tags. And furthermore, get rid of first folder if it is not named "screenshots". Is there a simple way to do this in one go?


This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="image/@href[starts-with(.,'./screenshots/')]">
  <xsl:attribute name="href">
   <xsl:value-of select="substring(.,3)"/>
  </xsl:attribute>
 </xsl:template>

  <xsl:template match=
   "image/@href
     [starts-with(.,'./')
     and not(starts-with(substring(.,3), 'screenshots/'))
     ]">
  <xsl:attribute name="href">
   <xsl:value-of select="substring-after(substring(.,3),'/')"/>
  </xsl:attribute>
 </xsl:template>


 <xsl:template priority="10"
      match="image/@href[starts-with(.,'./views/')]">
  <xsl:attribute name="href">
   <xsl:value-of select="substring(.,9)"/>
  </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

   <t>
    <image href="./views/screenshots/page1.png"/>
    <image href="./screenshots/page2.png"/>
    <load href="./xxx.yyy"/>
    <image href="ZZZ/screenshots/page1.png"/>
   </t>

produces the wanted result:

<t>
    <image href="screenshots/page1.png"/>
    <image href="screenshots/page2.png"/>
    <load href="./xxx.yyy"/>
    <image href="ZZZ/screenshots/page1.png"/>
</t>

Do note:

  1. The use and overriding of the identity rule. This is the most fundamental and most powerful XSLT design pattern.

  2. Only href attributes of image elements are modified.

  3. Only href attributes that start with the string "./" or the string "./{something-different-than-screenshots}/" are processed in a special way (by separate templates).

  4. All other nodes are only processed by the identity template.

  5. This is a pure "push style" solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消