xml - 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 文件。
解决方案
怎么样:
<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>
推荐阅读
- javascript - 从另一个页面获取信息到 javascript
- firebase - 错误:找不到 com.google.firebase.iid.zzb 无法访问 zzb 类文件
- sparql - SPARQL 查询返回同一个人的多个出生日期
- powershell - 通过 Active Directory 查询删除“-”之前的字符
- android - 如何更正警告“Drive.API 已弃用”?
- css - 谷歌字体文件大小下载与 CDN
- c# - 我可以让这段代码更简单、更小吗?C#
- c++ - 直接给浮点变量赋值十六进制整数和通过指针转换赋值的区别
- python - 用 Python 解析一个非常大的文本文件?
- java - Heroku:如何为非 java 项目安装 openjdk-8-jdk?