gpt4 book ai didi

php - 使用 xslt 获取属性节点并打印不同的值

转载 作者:可可西里 更新时间:2023-10-31 23:08:04 26 4
gpt4 key购买 nike

<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取出不同的值。意味着它会打印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,40,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);

另见

关于php - 使用 xslt 获取属性节点并打印不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12155431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com