xslt - XSLT:复制子元素与属性匹配的元素
问题描述
很明显,这个问题的一个变体以前已经被问过很多次了。我已经筛选了许多其他问题,但似乎仍然找不到答案。
给定一个如下所示的 XML 文档:
<Media Attribute="4">
<Printed SomeAttribute="3">
<Book ID="1" OtherAttribute="2">
<Author ID="A">Author Name1</Author>
<Title>Some Title</Title>
</Book>
<Book ID="2" OtherAttribute="2">
<Author ID="A">Author Name2</Author>
<Title>Another Book Name</Title>
</Book>
</Printed>
</Media>
我正在寻找@ID="1"
使输出看起来如下所示的书:
<Media Attribute="4">
<Printed SomeAttribute="3">
<Book ID="1" OtherAttribute="2">
<Author ID="A">Author Name1</Author>
<Title>Some Title</Title>
</Book>
</Printed>
</Media>
我尝试了以下不同的变体,但它不起作用:
<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="*"/>
<xsl:template match="Media">
<xsl:copy>
<xsl:copy-of select="@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/Media/Printed/Book[@ID='1']]">
<xsl:copy>
<xsl:copy-of select="@*" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
我可以成功复制根节点,并且可以Book
使用递归成功复制元素copy-of
,但我不确定如何以Media/Printed
非递归方式匹配/选择父节点(),同时还使用Book
递归复制元素。
非常感谢!
解决方案
如何以
Media/Printed
非递归方式匹配/选择父节点()
为什么不一直递归地做:
XSLT 1.0
<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="Printed">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="Book[@ID='1']"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
或者,您可以这样做:
<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="*"/>
<xsl:template match="/Media">
<xsl:copy>
<xsl:copy-of select="@*"/>
<Printed>
<xsl:copy-of select="Printed/@*"/>
<xsl:copy-of select="Printed/Book[@ID='1']"/>
</Printed>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- sql-server - 从同一网络域 PC 从 Access 2013 连接到 SQL Server 2017 时,多步 OLE DB 操作生成错误
- database - 我可以在浏览器中创建数据库吗?除了 localstorage/indexedDB/session 存储
- wordpress - 如何使用 getChildHtml() 从 Magento 获取块并将其插入 Wordpress 标题?
- reactjs - 有没有办法从父组件访问formik的提交函数、值和其他道具
- sql-server - Hibernate 一对多准备好的语句非常慢
- c++ - 最后打印所有类实例方法的打印语句?
- python - 有没有办法说“如果有什么==什么”?(Python)
- audio - FFMPEG:无法从 RTSP 摄像机 IP:V380 Pro 获取音频流
- python - 拆分字符串,中间有 2 个空格
- matlab - 以下代码的矢量化有什么好处吗?