gpt4 book ai didi

xslt - 使用 XSLT 将节点值相乘

转载 作者:行者123 更新时间:2023-12-03 16:06:06 25 4
gpt4 key购买 nike

我需要获取来自同一个 XML 文件中两个不同节点的值。例如,我的 xml:

 <asset>
<curr_wanted>EUR</curr_wanted>
<curr>USD</curr>
<value>50</value>
</asset>

<exchangeRates>
<USD>
<USD>1</USD>
<EUR>0.73</EUR>
</USD>
</exchangeRates>

我想得到相当于 50 美元的欧元。

我试过 :
<xsl:value-of select="(Asset/value * /exchangeRates[node() = curr]/curr_wanted)"/>

但它没有用。我还必须使用 XSLT 1.0。我怎样才能得到欧元的值(value)?

最佳答案

我没有对它进行太多测试,但是对于像这样的输入

<?xml version="1.0" encoding="UTF-8"?>
<root>
<asset>
<curr_wanted>EUR</curr_wanted>
<curr>USD</curr>
<value>50</value>
</asset>
<asset>
<curr_wanted>EUR</curr_wanted>
<curr>USD</curr>
<value>25</value>
</asset>
<exchangeRates>
<USD>
<USD>1</USD>
<EUR>0.73</EUR>
</USD>
</exchangeRates>
</root>

像下面这样的东西可以工作
for $asset in /root/asset, $rate in /root/exchangeRates 
return $asset/value*$rate/*[name() = $asset/curr]/*[name() = $asset/curr_wanted]

但它只能在 xpath 2.0 中工作,而且它还取决于整个输入 xml(比如是否可能存在更多 Assets 元素、更多 exchangeRates 元素等)。

编辑:在 xslt 1.0 中,您可以使用 xsl:variable 来存储一些信息并防止它们在 xpath 评估期间发生上下文更改。例如看下面的模板
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="text" />

<!-- Store "exchangeRates" in a global variable-->
<xsl:variable name="rates" select="/root/exchangeRates" />

<xsl:template match="/root">
<xsl:apply-templates select="asset" />
</xsl:template>

<xsl:template match="asset">
<!-- Store necessary values into local variables -->
<xsl:variable name="currentValue" select="value" />
<xsl:variable name="currentCurrency" select="curr" />
<xsl:variable name="wantedCurrency" select="curr_wanted" />
<xsl:variable name="rate" select="$rates/*[name() = $currentCurrency]/*[name() = $wantedCurrency]" />

<!-- Some text to visualize results -->
<xsl:value-of select="$currentValue" />
<xsl:text> </xsl:text>
<xsl:value-of select="$currentCurrency" />
<xsl:text> = </xsl:text>

<!-- using variable to prevent context changes during xpath evaluation -->
<xsl:value-of select="$currentValue * $rate" />

<!-- Some text to visualize results -->
<xsl:text> </xsl:text>
<xsl:value-of select="$wantedCurrency" />

<xsl:text>&#10;</xsl:text>
</xsl:template>

</xsl:stylesheet>

它为上面的输入 xml 产生以下输出。
50 USD = 36.5 EUR
25 USD = 18.25 EUR

关于xslt - 使用 XSLT 将节点值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743131/

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