簡體   English   中英

將子節點復制到其父級的同級子節點中

[英]Copying a Child Node into its Parent's Sibling's Child Node

我剛剛開始學習將XLS用於XML到XML的轉換,所以也許這是新手,但是似乎無法在單個XSLT迭代中獲得我想要的轉換,並且無法在此特定對象上找到任何東西。物。
這是我得到的:

源XML:

<data>
<a/>
<b>
  <b1>ID#1</b1>
  <b2>
    <b2_1/>
  </b2>
</b>
<c>
  <b1>ID#1</b1>
  <b2_2/>
</c>
<!-- b and c nodes keep repeating with the same structure for different b1 IDs -->
</data>

我需要做的是將<b2_2>節點及其內容從<c>節點移動到特定 <b>節點的子節點b/b1的值等於c/b1的值。
因此,如果父節點共享具有相同值的特定元素,則將其子節點移至表兄弟節點。

所需結果:

<data>
<a/>
<b>
  <b1>ID#1</b1>
  <b2>
    <b2_1/>
    <b2_2/>
  </b2>
</b>
</data>

當前的XSLT:

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

<xsl:template match="b">
  <xsl:variable name="id1" select="b1"  />
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
    <xsl:apply-templates select="following-sibling::c[b1=$id1]/b2_2"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="c"/>

此代碼完成了一部分工作-將目標<b2_2>節點移至目標<b>節點,同時清理了冗余的<c>節點。

我現在得到的是

<data>
<a/>
<b>
  <b1>ID#1</b1>
  <b2>
    <b2_1/>
  </b2>
  <b2_2/>
</b>
</data>

我可以看到如何使用兩個XSLT文件分兩步進行所需的轉換,但是我覺得解決方案很簡單而且很簡單。 無法確定將目標節點放置到應該位於其上的子節點的方式,因此將感謝在正確方向上的所有技巧。

怎么樣:

<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="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="b2">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:copy-of select="../following-sibling::c[1]/b2_2"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="c"/>

</xsl:stylesheet>

或者,如果您希望按b1值進行鏈接:

<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:key name="c" match="c" use="b1" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="b2">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:copy-of select="key('c', ../b1)/b2_2"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="c"/>

</xsl:stylesheet>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM