[英]How to relocate closing tags in XML using XSLT
我想知道如何使用XSLT在XML中重新定位結束標記。 通常情況下,所有事物似乎都使用匹配來使事情正常進行,但這似乎有所不同。 目的是在不直接更改XML文件的情況下獲得所需的輸出。 我只想使用XSLT創建所需的輸出。 下面的代碼已關閉,但沒有關閉管理器標簽。
XML:
<?xml version="1.0" encoding="UTF-8"?>
<x>
<y>
<z value="john" designation="manager"></z>
<z value="mike" designation="associate"></z>
<z value="dave" designation="associate"></z>
</y>
</x>
XSLT:
<?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="x">
<employees>
<xsl:apply-templates/>
</employees>
</xsl:template>
<xsl:template match="y">
<employee>
<xsl:apply-templates/>
</employee>
</xsl:template>
<xsl:template match="*[contains(@designation, 'manager')]">
<manager>
<xsl:attribute name="value">
<xsl:value-of select="@value"/>
</xsl:attribute>
</manager>
</xsl:template>
<xsl:template match="*[contains(@designation, 'associate')]">
<associate>
<xsl:value-of select="@value"/>
</associate>
</xsl:template>
</xsl:stylesheet>
所需的輸出:
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<manager value="john">
<associate>mike</associate>
<associate>dave</associate>
</manager>
</employee>
</employees>
您的問題不是關於“重新定位結束標記”。 它是關於通過將同級轉換為父級和子級來重新排列XML樹的層次結構的。 這可以通過以下方式完成:
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="*"/>
<xsl:template match="x">
<employees>
<xsl:apply-templates/>
</employees>
</xsl:template>
<xsl:template match="y">
<employee>
<xsl:apply-templates select="z[@designation='manager']"/>
</employee>
</xsl:template>
<xsl:template match="z[@designation='manager']">
<manager value="{@value}">
<xsl:apply-templates select="../z[@designation='associate']"/>
</manager>
</xsl:template>
<xsl:template match="z[@designation='associate']">
<associate>
<xsl:value-of select="@value"/>
</associate>
</xsl:template>
</xsl:stylesheet>
請注意,這是假設只有一名經理。 否則,所有員工將被列在不止一位經理的領導之下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.