how to get a transformed xml file with all child t

2019-07-07 04:21发布

I am using this input xml file .

                 <Content>
                <body><text>xxx</text></body>
                    <body><text>yy</text></body>
               <body><text>zz</text></body>
               <body><text>kk</text></body>
                   <body><text>mmm</text></body>
                        </Content>

after Xslt transformation the output should be

                        <Content>
                 <body><text>xxx</text>
                       <text>yy</text>
                           <text>zz</text>
                     <text>kk</text>
                   <text>mmm</text></body>
                     </Content>

Can anyone please provide its relavant Xsl file.

标签: xslt
2条回答
放荡不羁爱自由
2楼-- · 2019-07-07 04:27
    <xsl:template match="Content">
      <body>
            <xsl:apply-templates select="body/text"/>
      </body>
    </xsl:template>

  <xsl:template match="body/text">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
查看更多
倾城 Initia
3楼-- · 2019-07-07 04:34

This complete transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="body"/>
 <xsl:template match="body[1]">
  <body>
   <xsl:apply-templates select="../body/node()"/>
  </body>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<Content>
    <body>
        <text>xxx</text>
    </body>
    <body>
        <text>yy</text>
    </body>
    <body>
        <text>zz</text>
    </body>
    <body>
        <text>kk</text>
    </body>
    <body>
        <text>mmm</text>
    </body>
</Content>

produces the wanted, correct result:

<Content>
   <body>
      <text>xxx</text>
      <text>yy</text>
      <text>zz</text>
      <text>kk</text>
      <text>mmm</text>
   </body>
</Content>

Explanation:

  1. The identity rule copies every node "as-is".

  2. It is overriden by two templates. The first ignores/deletes every body element`.

  3. The second template overriding the identity template also overrides the first such template (that deletes every body element) for any body element that is the first body child of its parent. For this first body child only, a body element is generated and in its body all nodes that are children nodes of any body child of its parent (the current body elements and all of its body siblings) are processed.

查看更多
登录 后发表回答