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:
The use and overriding of the identity rule. This is the most fundamental and most powerful XSLT design pattern.
Only
hrefattributes ofimageelements are modified.Only
hrefattributes that start with the string"./"or the string"./{something-different-than-screenshots}/"are processed in a special way (by separate templates).All other nodes are only processed by the identity template.
This is a pure "push style" solution.
加载中,请稍侯......
精彩评论