求可提取深层嵌套元素的XSL代码(基于给定XML结构)
提取深层嵌套元素的XSL解决方案
没问题,我帮你写一段能轻松处理深层嵌套结构的XSL代码,不管你的<group>嵌套多少层都能搞定。针对你给出的XML结构,这里有两种常见场景的实现:
场景1:提取所有嵌套的<test>元素
不管<test>在多少层<group>里面,都能一次性全部提取出来:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 匹配XML根节点,初始化输出结构 --> <xsl:template match="/"> <extracted-tests> <!-- 使用XPath的`//test`选择所有层级的test元素,无视嵌套深度 --> <xsl:apply-templates select="//test"/> </extracted-tests> </xsl:template> <!-- 自定义每个test元素的输出格式 --> <xsl:template match="test"> <!-- 这里输出test的name属性,也可以直接复制整个元素 --> <test-item name="{@name}"/> <!-- 如果需要保留原test元素结构,替换成: <xsl:copy-of select="."/> --> </xsl:template> </xsl:stylesheet>
关键说明://test是XPath的「后代轴」语法,会自动遍历XML中所有层级的<test>元素,完美适配深层嵌套的场景。
场景2:提取所有嵌套的<group>元素(含层级信息)
如果需要提取所有分组,甚至想知道每个分组的嵌套深度,可以用这段代码:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <extracted-groups> <xsl:apply-templates select="//group"/> </extracted-groups> </xsl:template> <xsl:template match="group"> <group-details> <group-name><xsl:value-of select="@name"/></group-name> <!-- 计算当前group的嵌套深度:祖先group的数量+1 --> <nesting-depth><xsl:value-of select="count(ancestor::group) + 1"/></nesting-depth> </group-details> </xsl:template> </xsl:stylesheet>
进阶:精准提取特定分组下的元素
如果只需要提取某个特定分组(比如G3)下的深层元素,只需要修改XPath选择器:
- 提取
G3下所有test://group[@name='G3']//test - 提取
G5_1下所有子分组://group[@name='G5_1']//group
要是你还有更具体的需求,比如保留元素的原始嵌套结构,或者自定义输出格式,随时说就行~
内容的提问来源于stack exchange,提问作者Manuel
相关产品推荐
相关产品推荐

