XSLT:如何不变地复制父节点并转换子节点

Chr*_*ssy 5 xml xslt

我是 XSLT 的新手,所以这可能是非常基本的,但我真的很感激一些输入。我需要在我的 xml 中转换子节点,但同时保持父节点不变。我的 xml 看起来像这样:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<XMLTest xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xmlns:jfxpf="http://www.xfa.com/schema/xml-package" xmlns:xfa="http://www.xfa.com/schema/xfa-data">
    <result form="10"   version="4" resultid="23146" respondent="ycisxmir" authid="" date="2012-09-12 06:39:44" times="462">
        <Q0061 answerid="1">1</Q0061>
        <Q0060 answerid="2">2</Q0060>
        <QTXT1>1</QTXT1>
    </result>
</XMLTest>
Run Code Online (Sandbox Code Playgroud)

我需要保持两个顶级节点 XMLTest 和 result 不变,而子节点需要转换为更通用的格式,如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<XMLTest xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xmlns:jfxpf="http://www.xfa.com/schema/xml-package" xmlns:xfa="http://www.xfa.com/schema/xfa-data">
    <result form="10"   version="4" resultid="23146" respondent="ycisxmir" authid="" date="2012-09-12 06:39:44" times="462">
        <answer>Q0061</answer>
        <id>1</id>
        <value>1</value>
        <answer>Q0060</answer>
        <id>2</id>
        <value>2</value>
        <answer>QTXT1</answer>
        <value>1</value>
    </result>
</XMLTest>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的 xslt 看起来像这样:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>

    <xsl:template match="result/*">
        <answer><xsl:value-of select="local-name()"/></answer> 
        <id><xsl:value-of select="@answerid"/></id> 
        <value><xsl:value-of select="@*"/></value> 
    </xsl:template>  
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

我已经尝试在顶级节点上使用 xsl:copy ,但无法在不丢失子节点或子节点转换的情况下使其工作。如何保持顶部节点并同时强制通过转换后的子节点?

Mar*_*nen 3

从...开始

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

现在添加您需要的转换模板,即

<xsl:template match="result/*[@answerid]">
        <answer><xsl:value-of select="local-name()"/></answer> 
        <id><xsl:value-of select="@answerid"/></id> 
        <value><xsl:value-of select="."/></value>   
</xsl:template>

<xsl:template match="result/*[not(@answerid)]">
         <answer><xsl:value-of select="local-name()"/></answer> 
        <value><xsl:value-of select="."/></value>  
</xsl:template>
Run Code Online (Sandbox Code Playgroud)