gpt4 book ai didi

xslt-1.0 - xslt动态取值

转载 作者:行者123 更新时间:2023-12-02 05:10:12 27 4
gpt4 key购买 nike

如何进行动态取值?

是这样的:

1) 我们从系统 A 得到一个 XML 导出。
2) 我们选择并格式化了系统B需要的一些数据。
3)其中一个传递的字段需要从源xml的多个元素中组合。

组合元素可以由客户定制。

所以,我现在拥有的是:
用于从系统 A 转换 xml 的 XSLT
一个简单的配置 xml,客户可以在其中指定他想要按顺序组合的字段:

<items>
<field type="field">field1</field>
<field type="text">whatever the customer wants between the combined fields</field>
<field type="field">field2</field>
<field type="text">whatever the customer wants between/after the combined fields</field>
<field type="field">field3</field>
</items>

此 xml 的示例将转换为:

<field1>, <field2> and <field3> or <field1>+<field2>=<field3>

在我的 xslt 中我有这个:

<xsl:variable name="configfile" select="document(myconfigxml.xml)"/>

然后我使用 xslt 遍历字段类型和 @type='field' 我想使用字段的值来查看源 xml 的元素。

<xsl:template name="items">
<xsl:param name="personElementFromSourceXml"/>
<xsl:for-each select="$configfile/items/field">
<xsl:choose>
<xsl:when test="@type='field'">
<xsl:value-of select="???"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>

我需要在 ??? 的位置输入什么? ?在伪 xslt 中它将是 $personElementFromSourceXml/value-of-<field1-2-3>我尝试了很多东西,例如 concat($personElementFromSourceXml, '/', current()),尝试了 $personElementFromSourceXml/current(),但它们不起作用。

另外,在这里进行小的理智检查:我解决这个问题的想法是好的方法还是我违反了书中的每条规则?请注意,我还是 xslt 的新手。

最佳答案

您的想法是正确的,即通过元素名称的值来选择其内容的元素。如果我误解了您的问题,请原谅我,但我将“items”文件解释为模板文件并假设有一个单独的输入文件。例如。对于配置文件:

<items>
<field type="text">Here are the contents of bark: </field>
<field type="field">bark</field>
<field type="text">Here are the contents of woof: </field>
<field type="field">woof</field>
<field type="text">The end of the line.
</field>
</items>

对于源文件:

<file>
<woof>Woof! Woof!</woof>
<meow>Meow.</meow>
<bark>Bark! Bark!</bark>
</file>

我这样修改了你的代码:

<?xml version="1.0"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="configfile" select="document('config.xml')"/>
<xsl:variable name="srcfile" select="/"/>

<xsl:template match="/">
<xsl:for-each select="$configfile/items/field">
<xsl:choose>
<xsl:when test="@type='field'">
<xsl:variable name="tagname" select="."/>
<xsl:value-of select="$srcfile/descendant::*[local-name()=$tagname]"/>
<xsl:text>
</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

因为 xsl:for-each 遍历 $configfile/items/field,每个 field 元素都成为上下文节点,所以您需要一种明确引用源文件的方法,这就是我将其分配给全局变量的原因。我得到这个输出:

Here are the contents of bark: Bark! Bark!
Here are the contents of woof: Woof! Woof!
The end of the line.

关于xslt-1.0 - xslt动态取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387242/

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