我有一个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处理器,你需要稍微不同的东西)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。