1

我有一个 xml 文档,我需要用包含两个节点以及处理指令的部分 xml 段替换特定节点。我想保留 PI,但在更换时遇到了问题。

段示例:general.xml

<root>
  <!--General Settings -->
  <?mapping EnvironmentSetting="envname"?>
  <setting name="SubscriptionName" value="*" />
</root>

源代码:

<environment>
  <General />
</environment>

转换 -

<xsl:template match="* | processing-instruction() | comment()">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="*/General">
  <xsl:copy-of select="document('general.xml')/root"/>
</xsl:template>

输出是:

<environment>
  <root>
    <!--General Settings -->
    <?mapping EnvironmentSetting="envname"?>
    <setting name="SubscriptionName" value="*" />
  </root>
</environment>

但我想要:

<environment>
  <!--General Settings -->
  <?mapping EnvironmentSetting="envname"?>
  <setting name="SubscriptionName" value="*" />
</environment>

将文档部分更改为 root/* 会删除处理指令(和注释)

<xsl:copy-of select="document('general.xml')/root/*"/>
...
<environment>
  <setting name="SubscriptionName" value="*" />
</environment>

将文档部分更改为 root/process-instructions 会删除节点

<xsl:copy-of select="document('general.xml')/root/processing-instruction()"/>
...
<environment>
  <?mapping EnvironmentSetting="envname"?>
</environment>

试图做一个| 只匹配第一个参数 -

<xsl:copy-of select="document('general.xml')/root/processing-instruction() | * | comment()"/>
...
<environment>
  <?mapping EnvironmentSetting="envname"?>
</environment>

那么我怎样才能得到我的蛋糕并吃掉它呢?我看起来很接近,但是在找到任何我想做的事情的例子时遇到问题。

4

1 回答 1

0

这应该这样做:

<xsl:template match="* | processing-instruction() | comment()">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="*/General">
  <xsl:apply-templates select="document('general.xml')/root"/>
</xsl:template>

<xsl:template match="root">
  <xsl:apply-templates select="node() | @*"/>
</xsl:template>

或者,您可以使用联合运算符复制几种类型的节点:

<xsl:template match="*/General">
  <xsl:variable name="r" select="document('general.xml')/root" />
  <xsl:apply-templates select="$r/* | $r/processing-instruction() | $r/comment()" />
</xsl:template>
于 2014-04-22T05:53:25.157 回答