如果节点不存在,如何使用XSLT创建节点?我需要在下面插入节点,但是如果节点不存在,那么我也需要创建它。
例如:
输入(组节点存在):
<story>
<group>
<overhead>
<l1>overhead</l1>
</overhead>
<headline>
<l1>headline</l1>
</headline>
</group>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
输出:
<story>
<group>
<sectionhead />
<overhead>
<l1>overhead</l1>
</overhead>
<headline>
<l1>headline</l1>
</headline>
</group>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
输入(组节点不存在):
<story>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
输出:
<story>
<group>
<sectionhead />
</group>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
发布于 2011-06-13 21:10:33
尝试将问题描述中的规则直接转换为模板规则:
“我需要在<group>
下插入节点<sectionhead>
”
<xsl:template match="group">
<group>
<sectionhead/>
<xsl:apply-templates/>
</group>
</xsl:template>
但是,如果<group>
节点不存在,那么我也需要创建该节点。
<xsl:template match="story[not(group)]">
<story>
<group>
<sectionhead/>
</group>
<xsl:apply-templates/>
</story>
</xsl:template>
发布于 2011-06-13 21:47:33
下面是一个完整的解决方案,它覆盖了任何没有story
group
子级的元素的标识规则/模板:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="story[not(group)]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<group>
<sectionhead />
</group>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="group[not(sectionhead)]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<sectionhead />
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
在所提供的XML文档上应用时为(不带 group
**):**
<story>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
生成所需的正确结果::
<story>
<group>
<sectionhead/>
</group>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
应用于第一个XML文档(具有没有group
sectionhead
子级的)时的:
<story>
<group>
<overhead>
<l1>overhead</l1>
</overhead>
<headline>
<l1>headline</l1>
</headline>
</group>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
同样的转换再次产生想要的正确结果:
<story>
<group>
<sectionhead/>
<overhead>
<l1>overhead</l1>
</overhead>
<headline>
<l1>headline</l1>
</headline>
</group>
<text>
<lines>
<l1>line</l1>
</lines>
</text>
</story>
发布于 2011-06-13 19:58:54
<xsl:for-each select="//story/group">
<sectionhead />
<xsl:copy-of select="." />
</xsl:for-each>
<xsl:for-each select="//story/text">
<group><sectionhead /></group>
<xsl:copy-of select="." />
</xsl:for-each>
两个阶段-好吗?
https://stackoverflow.com/questions/6329843
复制相似问题