1

私はこれをしばらく探していて、多くのオプションを試しましたが、それらはすべて私が望むことを部分的に行います。これらを組み合わせて必要なものにするほど XSLT に精通していません。助けていただければ幸いです。

私のxml

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <id>1</id>
    <child>
        <a>sample</a>
    </child>
</parent>

<parent>
    <id>2</id>
    <child>
        <a>sample</a>
    </child>
</parent>     

出力は次のようになります。

<parent>
    <id>1</id>
    <child>
        <id>1</d>
        <a>sample</a>
    </child>
</parent>

<parent>
    <id>2</id>
    <child>
        <id>2</id>
        <a>sample</a>
    </child>
</parent>

必要なことを行うxslコードを見つけましたが、属性をコピーしますが、ID内の番号をコピーする必要があります(IDを属性にするオプションではありません)。また、それらはすべて同じであるため、xlsがどの親/ IDをどの子に接続する必要があるかを知ることができるかどうかも疑問です。

4

1 に答える 1

0

入力 XML にはルート要素がないと思われるため、次の入力 XML を使用しました。

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <parent>
        <id>1</id>
        <child>
            <a>sample</a>
        </child>
    </parent>
    <parent>
        <id>2</id>
        <child>
            <a>sample</a>
        </child>
    </parent>
</data>

この XSLT を適用すると:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!-- Identity to copy all elements -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <!-- Match on element child and copy this element, but on top add a new element
          <id> and fill this with the ancestor element called parent and it's child id -->
    <xsl:template match="child">
        <xsl:copy>
            <xsl:apply-templates select="@*" /> <!-- Copy attributes first because we will add a node after this -->
            <id><xsl:value-of select="ancestor::parent/id" /></id>
            <xsl:apply-templates select="node()" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

出力は次のようになります。

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <parent>
        <id>1</id>
        <child>
            <id>1</id>
            <a>sample</a>
        </child>
    </parent>
    <parent>
        <id>2</id>
        <child>
            <id>2</id>
            <a>sample</a>
        </child>
    </parent>
</data>
于 2013-09-25T14:25:17.013 に答える