2017-08-22 10 views
0

XSLTを使用してXMLで終了タグを再配置する方法を知りたいと思います。通常、すべてが一致を使用して動作させるように見えますが、これは異なるようです。目標は、XMLファイルを直接変更することなく、望ましい出力を得ることです。私は、XSLTを使用してのみ、目的の出力を作成したい。以下のコードは近いですが、マネージャータグは閉じません。XSLTを使用してXMLで終了タグを再配置する方法

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> 
+0

タグではなく、ツリーを考えよう!入力の構造のツリー図と出力の構造のツリー図を描きます。 XSLTはツリーの変換に関するものであり、タグの並べ替えに関するものではありません。 –

答えて

0

あなたの質問は、 "終了タグの再配置" に関するものではありません。それは、兄弟を親と子に変換することによって、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> 

注意。そうしないと、すべてのアソシエートが複数のマネージャに表示されます。

関連する問題