[英]Replace a part of attribute in XML using XSLT 2.0
I want to replace every occurrence of cc_2 in id with cc_0 when name in key tag ='AFI' using XSLT.当使用 XSLT 的 key tag ='AFI' 中的 name 时,我想用 cc_0 替换 id 中的每个 cc_2。 I am unable to figure out how should I traverse or scan the entire XML when 'AFI' is found.当找到“AFI”时,我无法弄清楚我应该如何遍历或扫描整个 XML。 I wanted to use replace but not able to do so.我想使用替换但不能这样做。
Input XML输入 XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hhs>
<hh id="cc_2_1">
<ad>
<e>
<key>PP</key>
<value>/P</value>
</e>
</ad>
<cc>cc_2</cc>
<name>O</name>
<recs>
<rec id="cc_2_rec_32_18">
<ads/>
</rec>
<rec id="cc_2_rec_32_185">
<keys>
<key>
<name>AFI</name>
</key>
</keys>
<ads/>
<keys>
<key>
<name>AFI</name>
</key>
</keys>
</rec>
</hh>
</hhs>
Output XML Output XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hhs>
<hh id="cc_0_1">
<ad>
<e>
<key>PP</key>
<value>/P</value>
</e>
</ad>
<cc>cc_0</cc>
<name>O</name>
<recs>
<rec id="cc_0_rec_32_18">
<ads/>
</rec>
<rec id="cc_0_rec_32_185">
<keys>
<key>
<name>AFI</name>
</key>
</keys>
<ads/>
<keys>
<key>
<name>AFI</name>
</key>
</keys>
</rec>
</hh>
</hhs>
For the attribute change I think you want something along the lines of对于属性更改,我认为您想要一些类似的东西
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="*[.//key/name = 'AFI']//*/@id[starts-with(., 'cc_2')]">
<xsl:attribute name="{name()}" select="replace(., '^cc_2', 'cc_0')"/>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/gVhEait https://xsltfiddle.liberty-development.net/gVhEait
If the cc
element needs to be transformed to:如果cc
元素需要转换为:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="*[.//key/name = 'AFI']//*/@id[starts-with(., 'cc_2')]">
<xsl:attribute name="{name()}" select="replace(., '^cc_2', 'cc_0')"/>
</xsl:template>
<xsl:template match="*[.//key/name = 'AFI']//cc">
<xsl:copy>
<xsl:value-of select="replace(., 'cc_2', 'cc_0')"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/gVhEait/1 https://xsltfiddle.liberty-development.net/gVhEait/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.