XSLT - retrieving an XMl tag value without its inner tags

自古美人都是妖i 提交于 2019-12-11 08:04:37

问题


I have an xml that looks like this:

<OuterTag> outerVal
   <Name> value1 </Name>
   <Desc> value2 </Desc>
</OuterTag>

and I want to retrieve the value of the outer tag ("outerVal"). when I use

xsl:value-of select="OuterTag" />

I get "outerValvalue1value2". How can i retrieve only the outer value?


回答1:


A complete solution:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output omit-xml-declaration="yes" method="text"/>
    <xsl:template match="/">
        <xsl:value-of select="normalize-space(OuterTag/text()[1])" />
    </xsl:template>
</xsl:stylesheet>

Output:

outerVal

Note: Whitespace is significant inside XML elements. Here's a stylesheet that reveals the placement/structure of the text nodes in OuterTag and its children:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" method="text" />
    <xsl:template match="OuterTag/text()">
        <xsl:value-of select="concat('[', ., ']')" />
    </xsl:template>
    <xsl:template match="OuterTag/*/text()">
        <xsl:value-of select="concat('(', ., ')')" />
    </xsl:template>
</xsl:stylesheet>

Output:

[ outerVal
   ]( value1 )[
   ]( value2 )[
]

Adding normalize-space:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" method="text" />
    <xsl:template match="OuterTag/text()">
        <xsl:value-of select="concat('[', normalize-space(), ']')" />
    </xsl:template>
    <xsl:template match="OuterTag/*/text()">
        <xsl:value-of select="concat('(', normalize-space(), ')')" />
    </xsl:template>
</xsl:stylesheet>

Produces the following result:

[outerVal](value1)[](value2)[]



回答2:


Try text():

<xsl:value-of select="OuterTag/text()" />



回答3:


Use this: <xsl:value-of select="OuterTag/text()"/>




回答4:


Adapt this xpath to your context

 "/Outertag/text()[1]"

This will retrieve the first text node of the Outertag root node. The other answers show you how to get all text children nodes of Outertag context node.



来源:https://stackoverflow.com/questions/6744077/xslt-retrieving-an-xml-tag-value-without-its-inner-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!