Take the node attribute and print a specific value using xslt

<page> <tab dim="70"></tab> <tab dim="40"></tab> <tab dim="30"></tab> <tab dim="30"></tab> <tab dim="30"></tab> <tab dim="70"></tab> </page> 

how to get the value of tab dim attributes and render a great value using xslt.means, it will print 30,40,70

+4
source share
2 answers

To select different attribute values, you can use this XPath:

 /page/tab[not(@dim=preceding-sibling::tab/@dim)]/@dim 

A possible XSLT template would be

 <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:template match="/"> <xsl:for-each select="/page/tab[not(@dim=preceding-sibling::tab/@dim)]/@dim"> <xsl:sort select="." data-type="number"/> <xsl:value-of select="concat(., substring(',', 2 - (position() != last())))"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> 

To convert the source stylesheet document to PHP , you can use:

 $xml = new DOMDocument; $xml->load('collection.xml'); $xsl = new DOMDocument; $xsl->load('collection.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); echo $proc->transformToXML($xml); 

This will give 30.40.70 output.

You can achieve the same without XSLT by simply doing:

 $page = simplexml_load_file('NewFile.xml'); $dims = $page->xpath('/page/tab[not(@dim=preceding-sibling::tab/@dim)]/@dim'); $dims = array_map('strval', $dims); sort($dims); echo implode(',', $dims); 

Also see

+3
source

Grouping using preceding-sibling::someName is slow known (O (N ^ 2) - quadratic) and can be prohibitive for use on large node networks.

Here is a simple and effective Muenchian grouping solution :

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:key name="kTabByDim" match="tab" use="@dim"/> <xsl:template match="/*"> <xsl:apply-templates select= "tab[generate-id()=generate-id(key('kTabByDim',@dim)[1])]"> <xsl:sort select="@dim" data-type="number"/> </xsl:apply-templates> </xsl:template> <xsl:template match="tab"> <xsl:if test="position() >1">,</xsl:if> <xsl:value-of select="@dim"/> </xsl:template> </xsl:stylesheet> 

When this conversion is applied to the provided XML document:

 <page> <tab dim="70"></tab> <tab dim="40"></tab> <tab dim="30"></tab> <tab dim="30"></tab> <tab dim="30"></tab> <tab dim="70"></tab> </page> 

the desired, correct result is output:

 30,40,70 
+1
source

All Articles