加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – XSLT:如何不更改父节点并转换子节点

发布时间:2020-12-16 22:55:52 所属栏目:百科 来源:网络整理
导读:我是XSLT的新手,所以这可能是非常基本的,但我真的很感激一些输入.我需要转换我的xml中的子节点,但同时保持父节点不变.我的xml看起来像这样: ?xml version="1.0" encoding="UTF-8" standalone="yes"?XMLTest xmlns:xsi="http://www.w3.org/2000/10/XMLSchema
我是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>

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

<?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>

到目前为止,我的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>

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

解决方法

从…开始

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

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

<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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读