Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

Copy Node in XML to another position using XSLT

I try to replace a node if the value of it match with a node below. For doing this i need an xls transformation script.

How can i copy a XML Part into another?

<persons>
  <person>
    <name>Peter</name>
    <surname>Muster</surname>
    <address>
      <object>addresses/address1</object>
    </address>
  </person>
  <person>
    <name>Lisa</name>
    <surname>Muster</surname>
    <address>
      <object>addresses/address1</object>
    </address>
  </person>
  <person>
    <name>John</name>
    <surname>Smith</surname>
    <address>
      <object>addresses/address3</object>
    </address>
  </person>
<persons>
<addresses>
  <address1>
    <street>road1</street>
    <zip>66666</zip>
    <town>Moonvillage</town>
  </address1>
  <address2>
    <street>road2</street>
    <zip>77777</zip>
    <town>Sunvillage</town>
  </address2>
  <address3>
    <street>road3</street>
    <zip>88888</zip>
    <town>Venusvillage</town>
  </address3>
</addresses>

The result XML have to be like this:

<persons>
  <person>
    <name>Peter</name>
    <surname>Muster</surname>
    <address>
      <street>road1</street>
      <zip>66666</zip>
      <town>Moonvillage</town>
    </address>
  </person>
  <person>
    <name>Lisa</name>
    <surname>Muster</surname>
    <address>
      <street>road1</street>
      <zip>66666</zip>
      <town>Moonvillage</town>
    </address>
  </person>
  <person>
    <name>John</name>
    <surname>Smith</surname>
    <address>
      <street>road3</street>
      <zip>88888</zip>
      <town>Venusvillage</town>
    </address>
  </person>
<persons>

It's not necessary to delete the addresses in the final xml.

At the moment i try it with a match on "object" and copy-of. but since now it is not working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using XSLT 3 and support for xsl:evaluate (i.e. Saxon 10 all editions, Saxon-JS 2, Saxon 9.8 and 9.9 commercial editions, Altova XMLSpy/Raptor) it might be solvable as

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  expand-text="yes">

  <xsl:output method="xml" indent="yes"/>

  <xsl:mode on-no-match="shallow-copy"/>
  
  <xsl:template match="person/address">
    <xsl:copy>
      <xsl:evaluate xpath=". || '/*'" context-item="/*"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="addresses"/>

</xsl:stylesheet>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...