[英]How to loop through any XML and replace a specific Value using XSLT
我想创建一个XSLT转换,该转换遍历任何XML结构并替换特定值。 例如:
输入XML:
<?xml version="1.0" encoding="UTF-8"?>
<Node1>
<Node2>
<Node3>
<Tag1>1</Tag1>
<Tag2>2</Tag2>
<Tag3>3</Tag3>
</Node3>
</Node2>
</Node1>
假设我想用“ 1”替换任何值“ 2”
预期的输出XML:
<?xml version="1.0" encoding="UTF-8"?>
<Node1>
<Node2>
<Node3>
<Tag1>1</Tag1>
<Tag2>1</Tag2>
<Tag3>3</Tag3>
</Node3>
</Node2>
</Node1>
我已经尝试过使用xsl:for-each和xsl:if语句循环,但是它不起作用:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:copy-of select=".">
<xsl:for-each select=".">
<xsl:if test="xsl:value-of select = '2'">
xsl:value-of select = '1'
</xsl:if>
</xsl:for-each>
</xsl:copy-of>
</xsl:template>
</xsl:stylesheet>
我假设xsl:value-of部分不正确,但是我真的不知道如何在这种情况下访问Tag的值。
这似乎是一个奇怪的要求。 假设“值”表示元素中的文本节点(而不是属性的值),则可以简单地执行以下操作:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()[.='2']">
<xsl:text>1</xsl:text>
</xsl:template>
</xsl:stylesheet>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.