我正在寻找一种更简单,更优雅的方式来替换XML中的文本.对于源XML,例如:
<A>
<B>
<Name>ThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>NotThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>ThisOne</Name>
<Target>def</Target>
</B>
</A>
Run Code Online (Sandbox Code Playgroud)
我想将名称为"ThisOne"的所有Target元素的文本更改为"xyz".
结果将是:
<A>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target> <-- Changed.
</B>
<B>
<Name>NotThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target> <-- Changed.
</B>
</A>
Run Code Online (Sandbox Code Playgroud)
我完成了这个:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="B/Target">
<xsl:choose>
<xsl:when test="../Name/text()='ThisOne'"><Target>xyz</Target></xsl:when>
<xsl:otherwise><Target><xsl:value-of select="text()"/></Target></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
我在想这可以用<xsl:template match ="B/Target/text()">完成,所以我可以只替换文本而不是整个元素,但我无法弄清楚其余部分.
提前致谢.
这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="B[Name='ThisOne']/Target/text()">
<xsl:text>xyz</xsl:text>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
使用您的XML输入产生:
<A>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target>
</B>
<B>
<Name>NotThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target>
</B>
</A>
Run Code Online (Sandbox Code Playgroud)