仅处理选定的节点

whe*_*eph 2 xml xslt xslt-1.0

一个XSLT新手问题:我需要替换XML文件中的文本值.所有其他节点必须保持不变.这是我的输入文件(in.xml):

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <level1 attr1="val1">
        <level2>in</level2>
    </level1>
</root>
Run Code Online (Sandbox Code Playgroud)

这是我的XSLT转换(subst.xsl):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="//node()">
        <xsl:copy>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/root/level1/level2/text()">out</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

我使用以下Ant脚本(build.xml)运行它:

<?xml version="1.0" encoding="UTF-8"?>
<project name="test" default="test" basedir=".">
    <target name="test">
        <xslt style="subst.xsl" in="in.xml" out="out.xml" />
    </target>
</project>
Run Code Online (Sandbox Code Playgroud)

这是我得到的(out.xml):

<?xml version="1.0" encoding="UTF-8"?><root>
    <level1>
        <level2>out</level2>
    </level1>
</root>
Run Code Online (Sandbox Code Playgroud)

缺少"level1"的属性"attr1".

如果有人,我会非常感激

  • 告诉我subst.xsl有什么问题

要么

  • 让我知道如何强制xslt-processor 只是将非匹配节点复制到输出文件并手动完成(这在我的情况下容易出错).

jac*_*bit 11

您的身份转换缺少属性(显然).请改用:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

然后,只需添加您的上一个模板.