簡體   English   中英

在不同的父級下復制子節點

[英]Copying Child Nodes under different Parent

我是XSLT的新手並且遇到了這個問題。
輸入XML

<Root>
 <Family>
   <Entity>
     <SomeElement1/>
     <Child1>
       <Element1/>
     </Child1>
     <Child2>
       <Element2/>
     </Child2>
     <Entity>
     <SomeElement1/>
     <Child1>
       <Element111/>
     </Child1>
     <Child2>
       <Element222/>
     </Child2>
   </Entity>
  </Entity>
 </Family>
</Root>

輸出Xml

<Response>
 <EntityRoot>
  <SomeElement1/>
 </EntityRoot>

 <Child1Root>
   <Element1>
 </Child1Root>

 <Child2Root>
   <Element2>
 </Child2Root>

 <MetadataEntityRoot>
  <SomeElement1/>
 </MetadataEntityRoot>

 <Child1Root>
   <Element111>
 </Child1Root>

 <Child2Root>
   <Element222>
 </Child2Root>
</Response>

我知道如何從輸入xml中復制所有內容。 但不確定如何排除子元素,然后在不同的根元素中再次復制它們。

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

根據給出的答案嘗試了這個

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
   </xsl:template>
    <xsl:template match="Entity">
      <EntityRoot>
        <xsl:apply-templates select="@* | node()[not(self::Child1 | self::Child2)]" />
      </EntityRoot>
      <xsl:apply-templates select="Child1 | Child2" />
    </xsl:template>
    <xsl:template match="Child1">
      <Child1Root><xsl:apply-templates select="@*|node()" /></Child1Root>
    </xsl:template>
    <xsl:template match="Child2">
      <Child2Root><xsl:apply-templates select="@*|node()" /></Child2Root>
    </xsl:template>
</xsl:stylesheet>

但得到的輸出為:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
 <Family>
   <EntityRoot>
     <SomeElement1/>
   </EntityRoot>
   <Child1Root>
       <Element1/>
    </Child1Root>
    <Child2Root>
       <Element2/>
    </Child2Root>
 </Family>
</Root>

除了您已經擁有的“復制所有內容”標識模板之外,您只需添加與要以不同方式處理的元素匹配的特定模板。 要重命名Child1Child1Root可以使用

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

類似地將Child2重命名為Child2Root ,將Root重命名為Response 對於Entity你能想到的過程中,創建一個EntityRoot除了 Child1和CHILD2的所有子元素,然后應用模板,這兩個后來,外面的(應用模板的結果) EntityRoot元素:

<xsl:template match="Entity">
  <EntityRoot>
    <xsl:apply-templates select="@* | node()[not(self::Child1 | self::Child2)]" />
  </EntityRoot>
  <xsl:apply-templates select="Child1 | Child2" />
</xsl:template>

要完全剝離圖層(在本例中為Family )但仍包含其子圖層,您可以使用不帶copy的模板:

<xsl:template match="Family">
  <xsl:apply-templates />
</xsl:template>

暫無
暫無

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

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