xml – XSLT转换以添加多个不存在的子元素
发布时间:2020-12-16 23:17:50 所属栏目:百科 来源:网络整理
导读:我有一个xml文档,看起来像这样: p c1 / c2 //p 子元素c1和c2是可选的,但是对于处理步骤,我需要它们存在.所以我试图创建一个xslt样式表来将它们添加为空元素(子元素的顺序无关紧要). 这是我的样式表: xsl:template match="@*|node()" xsl:copy xsl:apply-te
我有一个xml文档,看起来像这样:
<p> <c1 /> <c2 /> </p> 子元素c1和c2是可选的,但是对于处理步骤,我需要它们存在.所以我试图创建一个xslt样式表来将它们添加为空元素(子元素的顺序无关紧要). 这是我的样式表: <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="p[not(c1)]"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <c1 /> </xsl:copy> </xsl:template> <xsl:template match="p[not(c2)]"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <c2 /> </xsl:copy> </xsl:template> 只要缺少一个子元素,这样就可以正常工作.但如果两者都丢失,则只创建c1.如何防止这种情况并强制创建c1和c2(实际上,大约有10个孩子)? 谢谢. 解决方法
我会这样做:
<xsl:template match="p"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <xsl:if test="not(c1)"> <c1 /> </xsl:if> <xsl:if test="not(c2)"> <c2 /> </xsl:if> </xsl:copy> </xsl:template> 如果您有一个较长的可能子节点列表,您可以将它们放在一个变量中,并使用for-each而不是个体,如果: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"> <xsl:output method="xml" indent="yes"/> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:variable name="childrenFragment"> <c1/> <c2/> </xsl:variable> <xsl:template match="p"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <xsl:variable name="this" select="."/> <xsl:for-each select="msxsl:node-set($childrenFragment)/*"> <xsl:variable name="localName" select="local-name()"/> <xsl:if test="not($this/*[local-name()=$localName])"> <xsl:element name="{$localName}"/> </xsl:if> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet> 只需在childrenFragment变量中添加所需的所有元素. (msxsl:node-set stuff是特定于Microsoft的,如果你使用的是另一个XSLT处理器,你需要稍微不同的东西) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |