Identity transform

The identity transform is a data transformation that copies the source data into the destination data without change.

The identity transformation is considered an essential process in creating a reusable transformation library. By creating a library of variations of the base identity transformation, a variety of data transformation filters can be easily maintained. These filters can be chained together in a format similar to UNIX shell pipes.

Examples of recursive transforms

The "copy with recursion" permits, changing little portions of code, produce entire new and different output, filtering or updating the input. Understanding the "identity by recursion" we can understand the filters.

Using XSLT

The most frequently cited example of the identity transform (for XSLT version 1.0) is the "copy.xsl" transform as expressed in XSLT. This transformation uses the xsl:copy command[1] to perform the identity transformation:

<xsl:stylesheet version="1.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:stylesheet>

This template works by matching all attributes (@*) and other nodes (node()), copying each node matched, then applying the identity transformation to all attributes and child nodes of the context node. This recursively descends the element tree and outputs all structures in the same structure they were found in the original file, within the limitations of what information is considered significant in the XPath data model. Since node() matches text, processing instructions, root, and comments, as well as elements, all XML nodes are copied.

A more explicit version of the identity transform is:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|*|processing-instruction()|comment()">
    <xsl:copy>
      <xsl:apply-templates select="*|@*|text()|processing-instruction()|comment()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

This version is equivalent to the first, but explicitly enumerates the types of XML nodes that it will copy. Both versions copy data that is unnecessary for most XML usage (e.g., comments).

XSLT 3.0

XSLT 3.0[2] specifies an on-no-match attribute of the xsl:mode instruction that allows the identity transform to be declared rather than implemented as an explicit template rule. Specifically:

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:mode on-no-match="shallow-copy" />
</xsl:stylesheet>

is essentially equivalent to the earlier template rules. See the XSLT 3.0 standard's description of shallow-copy[3] for details.

Finally, note that markup details, such as the use of CDATA sections or the order of attributes, are not necessarily preserved in the output, since this information is not part of the XPath data model. To show CDATA markup in the output, the XSLT stylesheet that contains the identity transform template (not the identity transform template itself) should make use of the xsl:output attribute called cdata-section-elements.

cdata-section-elements specifies a list of the names of elements whose text node children should be output using CDATA sections. [1] For example:

<xsl:output method="xml" encoding="utf-8" cdata-section-elements="element-name-1 element-name-2"/>

Using XQuery

XQuery can define recursive functions. The following example XQuery function copies the input directly to the output without modification.

declare function local:copy($element as element()) {
  element {node-name($element)}
    {$element/@*,
     for $child in $element/node()
        return if ($child instance of element())
          then local:copy($child)
          else $child
    }
};

The same function can also be achieved using a typeswitch-style transform.

xquery version "1.0";

(: copy the input to the output without modification :)
declare function local:copy($input as item()*) as item()* {
for $node in $input
   return 
      typeswitch($node)
        case document-node()
           return
              document {
                local:copy($node/node())
              }
        case element()
           return
              element {name($node)} {

                (: output each attribute in this element :)
                for $att in $node/@*
                   return
                      attribute {name($att)} {$att}
                ,
                (: output all the sub-elements of this element recursively :)
                for $child in $node
                   return local:copy($child/node())

              }
        (: otherwise pass it through.  Used for text(), comments, and PIs :)
        default return $node
};

The typeswitch transform is sometime preferable since it can easily be modified by simply adding a case statement for any element that needs special processing.

Non-recursive transforms

Two simple and illustrative "copy all" transforms.

Using XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <xsl:copy-of select="."/>
  </xsl:template>
</xsl:stylesheet>

Using XProc

<p:pipeline name="pipeline" xmlns:p="http://www.w3.org/ns/xproc">
  <p:identity/>
</p:pipeline>

Here one important note about the XProc identity, is that it can take either one document like this example or a sequence of document as input.

More complex examples

Generally the identity transform is used as a base on which one can make local modifications.

Remove named element transform

Using XSLT

The identity transformation can be modified to copy everything from an input tree to an output tree except a given node. For example, the following will copy everything from the input to the output except the social security number:

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

  <!-- remove all social security numbers -->
  <xsl:template match="PersonSSNID"/>

Using XQuery

 declare function local:copy-filter-elements($element as element(), 
   $element-name as xs:string*) as element() {
   element {node-name($element) }
             { $element/@*,
               for $child in $element/node()[not(name(.)=$element-name)]
                  return if ($child instance of element())
                    then local:copy-filter-elements($child,$element-name)
                    else $child
           }
 };

To call this one would add:

$filtered-output := local:copy-filter-elements($input, 'PersonSSNID')

Using XProc

<p:pipeline name="pipeline" xmlns:p="http://www.w3.org/ns/xproc">
  <p:identity/>
  <p:delete match="PersonSSNID"/>
</p:pipeline>

See also

Further reading

  • XSLT Cookbook, O'Reilly Media, Inc., December 1, 2002, by Sal Mangano, ISBN 0-596-00372-2
  • Priscilla Walmsley, XQuery, O'Reilly Media, Inc., Chapter 8 Functions – Recursive Functions – page 109

References

Read other articles:

Численность населения республики по данным Росстата составляет 4 003 016[1] чел. (2024). Татарстан занимает 8-е место по численности населения среди субъектов Российской Федерации[2]. Плотность населения — 59,00 чел./км² (2024). Городское население — 76,72[3] % (2022)…

Events at the1987 World ChampionshipsTrack events100 mmenwomen200 mmenwomen400 mmenwomen800 mmenwomen1500 mmenwomen3000 mwomen5000 mmen10,000 mmenwomen100 m hurdleswomen110 m hurdlesmen400 m hurdlesmenwomen3000 msteeplechasemen4 × 100 m relaymenwomen4 × 400 m relaymenwomenRoad eventsMarathonmenwomen10 km walkwomen20 km walkmen50 km walkmenField eventsHigh jumpmenwomenPole vaultmenLong jumpmenwomenTriple jumpmenShot putmenwomenDiscus throwmenwomenHammer throwmenJavelin throwmenwomenCombined eve…

此條目可参照英語維基百科相應條目来扩充。 (2021年5月6日)若您熟悉来源语言和主题,请协助参考外语维基百科扩充条目。请勿直接提交机械翻译,也不要翻译不可靠、低品质内容。依版权协议,译文需在编辑摘要注明来源,或于讨论页顶部标记{{Translated page}}标签。 约翰斯顿环礁Kalama Atoll 美國本土外小島嶼 Johnston Atoll 旗幟颂歌:《星條旗》The Star-Spangled Banner約翰斯頓環礁地…

هنودمعلومات عامةنسبة التسمية الهند التعداد الكليالتعداد قرابة 1.21 مليار[1][2]تعداد الهند عام 2011ق. 1.32 مليار[3]تقديرات عام 2017ق. 30.8 مليون[4]مناطق الوجود المميزةبلد الأصل الهند البلد الهند  الهند نيبال 4,000,000[5] الولايات المتحدة 3,982,398[6] الإمارا…

Ця стаття потребує додаткових посилань на джерела для поліпшення її перевірності. Будь ласка, допоможіть удосконалити цю статтю, додавши посилання на надійні (авторитетні) джерела. Зверніться на сторінку обговорення за поясненнями та допоможіть виправити недоліки. Матер…

土库曼斯坦总统土库曼斯坦国徽土库曼斯坦总统旗現任谢尔达尔·别尔德穆哈梅多夫自2022年3月19日官邸阿什哈巴德总统府(Oguzkhan Presidential Palace)機關所在地阿什哈巴德任命者直接选举任期7年,可连选连任首任萨帕尔穆拉特·尼亚佐夫设立1991年10月27日 土库曼斯坦土库曼斯坦政府与政治 国家政府 土库曼斯坦宪法 国旗 国徽 国歌 立法機關(英语:National Council of Turkmenistan) 土…

Fictional character from EastEnders This article is about the 1991 EastEnders character. For the 2019 character, see Peggy Taylor (EastEnders). For the British tennis player, see Peggy Michell. For the author, see Margaret Mitchell. Soap opera character Peggy MitchellEastEnders characterBarbara Windsor as Peggy Mitchell (2008)Portrayed byJo Warne (1991)Barbara Windsor (1994–2016)Jaime Winstone (2022 flashback)Duration1991, 1994–2010, 2013–2016, 2022First appearanceEpisode 65030&#…

The Big HipAlbum studio karya SlankDirilisJuli 2008Direkam2007GenrePop, RockLabelSlank Records dan Universal Music IndonesiaKronologi Slank Slow But Sure (2007)Slow But Sure2007 The Big Hip (2008) Anthem For The Broken Hearted (2009)Anthem For The Broken Hearted2009 The Big Hip adalah album musik keenam belas karya Slank. Dirilis pada tahun 2008. Lagu utamanya di album ini ialah Seperti Para Koruptor dan Kilav. Daftar lagu Rock n' Roll Sora REBUT Seperti Para Koruptor Yumede Areba II Sexy Ca…

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2022. Beralih KodePenampilanGenreRas dan BudayaBahasaEnglishPembaruanMingguanDurasiSekitar 30 menitProduksiProduser<! - Untuk kredit produksi ->PenayanganTayang perdanaMei 2016PenyediaNational Public RadioSitus webSitus web resmiCode Switch adalah outlet …

Rushton Triangular Lodge Symbols and inscriptions on the '15' side Schematic diagram Plans and section of the lodge[1] The Triangular Lodge is a folly, designed by Sir Thomas Tresham and constructed between 1593 and 1597 near Rushton, Northamptonshire, England. It is now in the care of English Heritage. The stone used for the construction was alternating bands of dark and light limestone. The lodge is Grade I listed on the National Heritage List for England.[2] Tresham was a Roma…

Position in the British Navy Commander Littoral Strike Group (COMLSG)Official badge of COMLSGIncumbentCommodore Rob Pedresince May 2020Navy Command, Ministry of DefenceReports toCommander United Kingdom Strike ForceAppointerNaval SecretaryTerm lengthNot fixed (typically 2 years)Inaugural holderCommodore Hardress LloydFormation1965–current The Commander Littoral Strike Group (COMLSG) is a senior British Royal Navy Amphibious warfare appointment. COMLSG, who is based in Stonehouse Barracks,…

Bounds of a sequence Lower limit and upper limit redirect here. For the statistical concept, see Lower/upper confidence limits. This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (February 2019) (Learn how and when to remove this message) In mathematics, the limit inferior and limit superior of a sequence can be thought of as limiting (that is, eventual and extreme)…

American nuclear physicist (1919–1986) Leona WoodsWoods at the University of Chicago in 1946BornLeona Harriet Woods(1919-08-09)August 9, 1919La Grange, Illinois, U.S.DiedNovember 10, 1986(1986-11-10) (aged 67)Santa Monica, California, U.S.EducationUniversity of Chicago (BS, MS, PhD)Known forInvolvement in the Manhattan ProjectSpouses John Marshall ​ ​(m. 1943; div. 1966)​ Willard Libby ​ ​(m. 1966; died&…

فهد بن سعود بن عبد العزيز آل سعود معلومات شخصية الميلاد 1923الرياض، سلطنة نجد الوفاة 30 أكتوبر 2006 (83 سنة)الرياض،  السعودية مكان الدفن مقبرة العدل  مواطنة السعودية  الأب سعود بن عبد العزيز آل سعود  عائلة آل سعود  مناصب وزير الدفاع السعودي   في المنصب1957  – 1960  س…

Electricity from wind in one U.S. state 2003 US Department of Energy wind resource map of Maryland Wind power in Maryland, which has land-based and offshore resources, is in the early stages of development.[1][2][3] As of 2016, Maryland has 191 megawatts (MW) of wind powered electricity generating capacity, responsible for 1.4% of in-state generated electricity.[4] Two offshore wind farm projects that will supply wind-generated power to the state are underway. The…

Town in County Donegal, Ulster, Ireland Town in Ulster, IrelandRamelton Ráth MealtainTownBridge over the River Lennon in RameltonRameltonLocation in IrelandCoordinates: 55°02′08″N 7°38′44″W / 55.03562°N 7.64555°W / 55.03562; -7.64555CountryIrelandProvinceUlsterCountyCounty DonegalElevation20 m (70 ft)Population (2016)[1] • Urban1,266Irish Grid ReferenceC228212 Ramelton (rə-MEL-tun; Irish: Ráth Mealtain),[2] also Ra…

Species of amphibian Northern leopard frog Conservation status Least Concern  (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Amphibia Order: Anura Family: Ranidae Genus: Lithobates Species: L. pipiens Binomial name Lithobates pipiens(Schreber, 1782) Range of L. pipiens Lithobates pipiens[1][2][3][4] formerly Rana pipiens,[5][6] commonly known as the northern leopard frog, is a s…

Biological classification system The tree of life. Two domains of life are Bacteria (top branches) and Archaea (bottom branches, including eukaryotes). The two-domain system is a biological classification by which all organisms in the tree of life are classified into two domains, Bacteria and Archaea.[1][2][3] It emerged from development of knowledge of archaea diversity and challenges to the widely accepted three-domain system that classifies life into Bacteria, Archaea,…

Monumen Sebelas DigulisMonumen Sebelas DigulisInformasi umumLokasiPontianak, IndonesiaAlamatJl. Jenderal Ahmad Yani, Bansir Laut, Kec. Pontianak Tenggara, Kota Pontianak, Kalimantan Barat 78115Diresmikan10 November 1987; 36 tahun lalu (1987-11-10)PemilikRepublik Indonesia Monumen Sebelas Digulis Kalimantan Barat, disebut juga sebagai Tugu Digulis atau Tugu Bambu Runcing atau Tugu Bundaran Untan oleh warga setempat, merupakan sebuah monumen yang terletak di Bundaran Universitas Tanjungpura, …

Part of the metro system for the city of Mumbai, India Line 1 (Blue Line)CRRC Puzhen rakes of the Mumbai Metro Line 1OverviewOther name(s)Versova–Andheri–Ghatkopar corridorStatusOperationalOwnerMumbai Metro One Pvt Ltd (MMOPL)[1][2] Reliance Infrastructure (69%) Mumbai Metropolitan Region Development Authority (MMRDA) (26%) Veolia Transport (5%) LocaleMumbai, Maharashtra, IndiaTerminiVersovaGhatkoparStations12Websitereliancemumbaimetro.comServiceTypeRapid transitSystemMumbai …