我有一个 xsl 模板,可以替换一些 xml 值。 现在我希望这些值由我的代码动态生成。
Transformer trans = TransformerFactory.newInstance().newTransformer(new StreamSource(new File("foo.xsl"));
trans.transform(new StreamSource(new File("foo.xml"), new StreamResult(new File("output.xml")));
如何实现例如仅在 id=1 处替换名称?而且通过 javacode 动态提供该 id,而不是硬编码?
<?xml version="1.0"?>
<my:accounts xmlns:my="http://myns">
<my:account>
<my:name>alex</my:name>
<my:id>1</my:id>
</my:account>
<my:account>
<my:name>Fiona</my:name>
<my:id>2</my:id>
</my:account>
</my:accounts>
这会替换所有名称:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="http://myns">
<xsl:param name="propertyName" select="'alex'"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[local-name()='account']/*[local-name()='name']/text()[.='{$propertyName}']">
<xsl:text>johndoe</xsl:text>
</xsl:template>
</xsl:stylesheet>
最佳答案
这种转变:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="http://myns">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pId" select="2"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="my:name/text()">
<xsl:choose>
<xsl:when test="../../my:id = $pId">johndoe</xsl:when>
<xsl:otherwise><xsl:copy-of select="."/></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<my:accounts xmlns:my="http://myns">
<my:account>
<my:name>alex</my:name>
<my:id>1</my:id>
</my:account>
<my:account>
<my:name>Fiona</my:name>
<my:id>2</my:id>
</my:account>
</my:accounts>
产生想要的正确结果:
<my:accounts xmlns:my="http://myns">
<my:account>
<my:name>alex</my:name>
<my:id>1</my:id>
</my:account>
<my:account>
<my:name>johndoe</my:name>
<my:id>2</my:id>
</my:account>
</my:accounts>
说明:
使用全局范围
<xsl:param>
。尽管设置了默认值,但该值会被转换调用者指定的值覆盖。请注意,对于不同的 xslt 处理器(供应商),如何指定转换的外部参数值的问题有不同的答案。您需要阅读您所使用的特定 XSLT 处理器的文档,以获得针对您的特定情况的答案。
关于java - 用动态值替换 XSLT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13724507/