【发布时间】:2015-08-21 20:18:29
【问题描述】:
我正在尝试将两个节点添加到某些 xml 的外部,并将转换后的结果输出到 xml 文件。我无法让它工作。我的 xml 将是:
<message>
<!-- ...other nodes and elements in here, not always consistent -->
</message>
(编辑)预期的 XML:
<?xml version="1.0" encoding="utf-8"?>
<rootNode>
<submessage>
<message>
<!-- ...other nodes and elements in here, not always consistent -->
</message>
</submessage>
</rootNode>
下面是我尝试过但似乎不起作用的 xsl。关于如何添加两个节点“rootNode”和“子消息”并输出结果的任何想法?
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" />
<xsl:variable name="root" select="/" />
<xsl:variable name="filename" select="'testOutPut'" />
<xsl:template match="/">
<xsl:result-document href="{$filename}.xml" method="xml">
<rootNode>
<submessage>
<message>
<xsl:apply-templates select="@*|node()"/>
</message>
</submessage>
</rootNode>
</xsl:result-document>
</xsl:template>
<xsl:template match="DefaultNodes/*">
<xsl:variable name="sourceNode" select="$root/message/*[name() = name(current())]" />
<xsl:choose>
<xsl:when test="$sourceNode">
<xsl:copy-of select="$sourceNode" />
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="." />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/rootNode">
<Request xmlns="urn:NameSpace-Definition-Message"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<xsl:apply-templates select="@*|node()"/>
</Request>
</xsl:template>
</xsl:stylesheet>
编辑:另外,我在 xsl 转换方面是一个非常绿色的人,这是我的第一次尝试,我正在尝试将其用作在某些 xml 被消耗之前编辑/修改某些 xml 的解决方案。
【问题讨论】:
-
我是否正确,您尝试在单个转换中:1)将第一个转换输出到外部 XML 文件(并用 2 个额外元素包围您的文档)2)将此 XML 文件转换为别的 ?我问是因为我看到您创建了
rootNode(= 它不在您的源 XML 中)并且有一个与之匹配的模板。 -
@ColinMaudry 输出文件只是为了看看我的转换是否有效。在我的实际场景中,我只需将两个外部节点添加到 xml。我将在我的问题中添加一个预期的 xml 块