首页 > 解决方案 > XSLT:排除一个元素但保留它的子元素

问题描述

您好我想排除一个特定元素,在这种情况下<ph>并保留它的子元素。xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<p>
   <s>
      <ph>
         <w>this</w>
         <w>is</w>
         <w>my</w>
         <w>first</w>
         <w>sentence</w>
         <pc>.</pc>
      </ph>
   </s>
   <s>
      <ph>
         <w>this</w>
         <w>is</w>
         <w>my</w>
         <w>second</w>
         <w>sentence</w>
         <pc>.</pc>
      </ph>
   </s>
</p>

所需的输出:

<?xml version="1.0" encoding="UTF-8"?>
<p>
   <s>
      <w>this</w>
      <w>is</w>
      <w>my</w>
      <w>first</w>
      <w>sentence</w>
      <pc>.</pc>
   </s>
   <s>
      <w>this</w>
      <w>is</w>
      <w>my</w>
      <w>second</w>
      <w>sentence</w>
      <pc>.</pc>
   </s>
</p>

xsl代码:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
<xsl:template match="p|s|w|pc">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:copy-of select="p|s|w|pc"/>
            <xsl:apply-templates select="*/*[not(self::phr)]"/> 
        </xsl:copy> 
    </xsl:template>
</xsl:stylesheet>

问题是有时<ph>不存在时我会丢失子元素,或者与<ph>元素具有相同的 xml 文件。

标签: xmlxslt

解决方案


怎么样:

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

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

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

</xsl:stylesheet>

推荐阅读