微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用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>

如何获取tab的dim属性的值并使用xslt.means取出不同的值它将打印30,40,70

解决方法

要选择不同的属性值,可以使用此XPath:

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

可能的XSLT模板

<?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>

transform the source document with the stylesheet in PHP,您可以使用:

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

这将在输出中给出30,70.

只需执行以下操作即可在没有XSLT的情况下实现相同的目标:

$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);

另见

> 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐