代码之家  ›  专栏  ›  技术社区  ›  Ace

XSL智能搜索和替换

  •  1
  • Ace  · 技术社区  · 15 年前

    是否可以查找和替换XML元素的属性?我想更改a href指向的目录:

    来自:

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

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

    和来自:

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

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

    因此,通过去掉所有图像标记的href中的所有“./”,而只除去图像标记。而且,如果第一个文件夹没有被命名为“截图”,就去掉它。有一个简单的方法一次完成吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Dimitre Novatchev    15 年前

    这种转变:

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

    应用于此XML文档时 :

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

    产生想要的结果 :

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

    做笔记 :

    1. 标识规则的使用和覆盖 . 这是最基本和最强大的XSLT设计模式。

    2. 只有 href 属性 image 元素被修改 .

    3. 只有 HREF 以字符串开头的属性 "./" 或字符串 "./{something-different-than-screenshots}/" 以特殊方式处理 (通过单独的模板)。

    4. 所有其他节点仅由标识模板处理 .

    5. 这是一个纯粹的“推送式”解决方案 .