如何解决如何在XSLT中输出具有属性的节点的值?
如何在XSL中获取具有属性的元素的值?
这是我用来测试代码的示例。
<CD>
<a/> <!--N0#1-->
<b>text</b> <!--NO#2-->
<c YEAR="value"/> <!--NO#3-->
<d name="value" ou="aous">9.90</d> <!--NO#4-->
<e><f>text</f> <!--NO#5-->
<g>text</g></e>
<i><h>text</h> <!--NO#6-->
<h>text</h></i>
</CD>
我希望这NO#4部分可以给我这样的输出:
"d" : {
"@name" : "value","@ou" : "aous","VALUE_VARIABLE":"9.90"
}
我遇到的问题是我无法获取“ 9.90”元素。我怎样才能做到这一点?这是我的代码:
<xsl:for-each select="@*">
<xsl:choose>
<xsl:when test="position()=last()"> <!--check if current attribute is last-->
"@<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>"
</xsl:when>
<xsl:when test="./*"> <!--check if current element has child elements-->
"<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>"
</xsl:when>
<xsl:when test="(./*) and not(position()=last())">
"<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>",</xsl:when>
<xsl:otherwise>
"@<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>",</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
编辑-here您可以找到完整的代码。
解决方法
尝试这样的事情:
<xsl:variable name="q">"</xsl:variable>
<xsl:variable name="nl">
</xsl:variable>
<xsl:template match="*[@*]">
<xsl:value select="name()"/>{
<xsl:for-each select="@*">
<xsl:if test="position()!=1">,</xsl:if>
<xsl:value-of select="concat($q,'@',name(),$q,' : ',.,$q)"/>
</xsl:for-each>
<xsl:value-of select="concat($q,'VALUE_VARIABLE',$q)"/>
</xsl:template>
,
在属性的上下文中,可以使用以下方法获取其父元素的字符串值:
<xsl:value-of select=".."/>
当然,从父元素本身的上下文中获取它要容易得多,例如:
<xsl:template match="d">
<xsl:text>{"d" : {</xsl:text>
<xsl:for-each select="@*">
<xsl:text>"@</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>" : "</xsl:text>
<xsl:value-of select="."/>
<xsl:text>",</xsl:text>
</xsl:for-each>
<xsl:text>"VALUE_VARIABLE" : "</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"}}</xsl:text>
</xsl:template>
P.S。
<xsl:when test="./*">
对于一个属性永远不会为真。
已添加:
如果要使其更通用,请尝试以下操作:
<xsl:template match="*[@*]">
<xsl:text>{"</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>" : {</xsl:text>
<xsl:for-each select="@*">
<xsl:text>"@</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>" : "</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:if test="text()">
<xsl:text>,"VALUE_VARIABLE" : "</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:if>
<xsl:text>}}</xsl:text>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:template>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。