gpt4 book ai didi

xml - 尝试读取 xsl 中的 xml 元素值

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

我是新来的 XSL .我正在尝试使用 XSL 文件读取 XML 元素的值。我的 XML 文件是这样的:

<PersonList>
<Person>
<Name>person1</Name>
<Age>21</Age>
</Person>
<Person>
<Name>person2</Name>
<Age>21</Age>
</Person>
</PersonList>

我的 XSL 文件是这样的:
<xsl:stylesheet version="1.0" xmlns=...>
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml declaration="no" />
<xsl template match="/">
<PersonList>
<xsl:for-each select="PersonList/Person">
<Person>
<xsl:for-each select="*">
<xsl:variable name="elementName">
<xsl:value-of select="name(.)" />
</xsl:variable>
<xsl:variable name="elementValue">
???
</xsl:variable>
</xsl:for-each>
</Person>
</xsl:for-each>
</PersonList>
</xsl:template>
</xsl:stylesheet>

我应该如何更换 ???获取存储在 elementName 中的元素的值变量。我分别尝试了以下三行:
<xsl:value-of select="value(.)" /> 
<xsl:value-of select="value($elementName)" />
<xsl:value-of select="$elementName" />

但没有运气。请帮忙!

最佳答案

您的 ??????????????????可以 <xsl:value-of select="."/> (即上下文元素的字符串值。)它与 $elementName 没有联系。 .

你可以像这样更简洁地做到这一点:

<xsl:for-each select="*">
<xsl:variable name="elementName" select="name()"/>
<xsl:variable name="elementValue" select="string(.)"/>
</xsl:for-each>

但是你的模板真的很奇怪。您正在收集这些变量,但您没有对它们做任何事情——它们不会出现在输出中。你想得到什么输出?

使用 for-each一般是代码异味。在几乎所有情况下,您最好使用多个模板:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="no" />

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="Person/*">
<xsl:variable name="elementName" select="name()"/>
<xsl:variable name="elementValue" select="string(.)"/>
</xsl:template>

</xsl:stylesheet>

这种复制几乎所有内容并仅更改一点 xml 的模式非常常见且非常强大,您应该 learn how to use it .

关于xml - 尝试读取 xsl 中的 xml 元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16019678/

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