【发布时间】:2021-04-22 02:47:25
【问题描述】:
层次结构是 XML 格式,我使用 XSLT 来转换数据。
例如:如果层次结构有 4 个级别,而我想跳过其间的一个级别(比如第 3 级):
Level 1
Level 2
Level 3 - Skip this level
Level 4
Level 5
我应该使用什么元素来达到同样的效果?
附上我作为参考输入的示例 XML 文件
<?xml version="1.0" encoding="UTF-8"?>
<Hierarchy>
<Board>
<Name>President</Name>
<Id>ABCDE</Id>
<ParentId></ParentId>
<General>
<Name>President</Name>
<Description>Top level of the Hierarchy</Description>
<Template>LEVEL1</Template>
</General>
</Board>
<Board>
<Name>VP</Name>
<Id>EFGHI</Id>
<ParentId>ABCDE</ParentId>
<General>
<Name>VP</Name>
<Description>Below the President</Description>
<Template>LEVEL2</Template>
</General>
</Board>
<Board>
<Name>Department_Heads</Name>
<Id>JKLMN</Id>
<ParentId>EFGHI</ParentId>
<General>
<Name>Department_Heads</Name>
<Description>Reports to the VP</Description>
<Template>LEVEL3</Template>
</General>
</Board>
<Board>
<Name>Supervisors</Name>
<Id>OPQRS</Id>
<ParentId>JKLMN</ParentId>
<General>
<Name>Supervisors</Name>
<Description>Reports to the Reports to Dep Heads</Description>
<Template>LEVEL4</Template>
</General>
</Board>
<Board>
<Name>Employees</Name>
<Id>TUVWX</Id>
<ParentId>OPQRS</ParentId>
<General>
<Name>Department_Heads</Name>
<Description>Reports to the Reports to Dep Heads</Description>
<Template>LEVEL5</Template>
</General>
</Board>
</Hierarchy>
更新:我正在添加预期的输出和我当前使用的 xslt 转换。
预期的输出如下:
我目前使用的转换如下:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<Hierarchy>
<xsl:for-each select="Hierarchy/Board">
<xsl:if test="General/Template='LEVEL1'">
<xsl:variable name="Presidentchild" select="Id"/>
<Board>
<Name>
<xsl:value-of select="Name"/>
</Name>
<Template>PRESIDENT</Template>
<Description>
<xsl:value-of select = "General/Description"/>
</Description>
</Board>
</xsl:if>
</xsl:for-each>
<xsl:for-each select="//Board">
<xsl:if test="ParentId = $Presidentchild">
<xsl:if test="General/Template='LEVEL2'">
<Board>
<xsl:variable name="VPchild" select="Id"/>
<Name>
<xsl:value-of select="Name"/>
</Name>
<Template>VICE_PRESIDENT</Template>
<Description>
<xsl:value-of select = "General/Description"/>
</Description>
</Board>
</xsl:if>
</xsl:if>
</xsl:for-each>
</Hierarchy>
</xsl:template>
</xsl:stylesheet>
........直到最后一个元素。
预期的输出如下:
<?xml version="1.0" encoding="utf-8"?>
<Hierarchy>
<Board>
<Name>President</Name>
<Template>PRESIDENT</Template>
<Description>Top level of the Hierarchy</Description>
<Board>
<Name>VP</Name>
<Template>VICE_PRESIDENT</Template>
<Description>Below the President</Description>
</Board>
</Board>
</Hierachy>
... 直到最后一个元素。
【问题讨论】:
-
请发布minimal reproducible example 显示示例输入、预期输出和您当前的尝试。 -- 提示:如果你从 identity transform 模板开始,并为你想要“跳过”的关卡添加一个覆盖模板,这将是相当简单的——这个模板除了将模板应用到上下文元素的子元素。
-
@michael.hor257k :我已经更新了你提到的问题