how to get a transformed xml file with all child t

2019-07-07 04:33发布

问题:

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.

回答1:

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.



回答2:

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


标签: xslt