take attribute node and print distinct value using xslt
php, xml, xpath, xslt
Solution
To select the distinct 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 transform the source document with the stylesheet in 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 in the output.
You can achieve the same without an 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
- http://schlitt.info/opensource/blog/0704_xpath.html
- How do I generate a comma-separated list with XSLT/XPath?
- XPath 1.0 select distinct attribute of siblings
Problem
``` <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's dim attributes and take out the distinct value using xslt.means it will print 30,40,70