2013-04-21 94 views
3

我有喜欢的xml:如何返回节点的文本,而不子节点文本

<item id="1"> 
     <items> 
      <item id="2">Text2</item> 
      <item id="3">Text3</item> 
     </items>Text1 
</item> 

如何返回<item id="1">(“文本1”)的文本? <xsl:value-of select="item/text()"/>什么也没有返回。

我的XSLT是:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="w3.org/1999/XSL/Transform"> 

    <xsl:template match="/"> 
    <html> 
     <body> 
     <xsl:apply-templates select="item"/> 
    </body> 
    </html> 
    </xsl:template> 

    <xsl:template match="item"> 
    <xsl:value-of select="text()"/> 
    </xsl:template> 
</xsl:stylesheet> 

我不知道还有什么类型提交我的编辑

+0

这取决于当前的上下文是什么(即当前节点是什么)。在你的情况下,你必须定位在'item'元素的父项。您能否向我们展示您当前的XSLT,因为这会澄清事情。谢谢。 – 2013-04-21 18:56:25

+0

    \t  \t  \t \t 
    \t \t \t \t \t \t \t \t \t \t \t \t \t
\t \t
\t
  • \t \t \t
  • user2304996 2013-04-21 19:00:50

    +0

    你真的可以编辑你的问题来包含XSLT,而不是添加评论吗?谢谢! – 2013-04-21 19:03:49

    回答

    2

    这应该一般工作:

    <xsl:apply-templates select="item/text()" /> 
    

    纳入到你的XSLT:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
        <xsl:key name="item_key" match="item" use="."/> 
        <xsl:strip-space elements="*" /> 
    
        <xsl:template match="/"> 
        <html> 
         <body> 
         <ul> 
          <xsl:apply-templates select="item"/> 
         </ul> 
         </body> 
        </html> 
        </xsl:template> 
        <xsl:template match="item"> 
        <li> 
         <xsl:apply-templates select="text()"/> 
        </li> 
        </xsl:template> 
    </xsl:stylesheet> 
    

    当你的样品输入运行,其结果是:

    <html> 
        <body> 
        <ul> 
         <li>Text1 
    </li> 
        </ul> 
        </body> 
    </html> 
    

    或者,这应该工作以及:

    <xsl:copy-of select="item/text()" /> 
    
    +0

    感谢您的回答 – user2304996 2013-04-21 19:18:52

    3

    如何返回<item id="1">( '文本1')的文本? <xsl:value-of select="item/text()"/>什么也没有返回。

    item元素有一个以上的文本节点的孩子和他们的第一个恰好是所有空白一个 - 这就是为什么你会得到“没有”。

    一个测试是否节点的字符串值是不是所有的空白的方式是通过使用normalize-space()功能。

    在一个XPath表达式,你要想这

    /*/text()[normalize-space()][1] 
    

    这是一个完整的转型,其结果是所需的文本节点:

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

    当这转换应用于提供的XML文档:

    <item id="1"> 
         <items> 
          <item id="2">Text2</item> 
          <item id="3">Text3</item> 
         </items>Text1 
    </item> 
    

    的希望,正确的结果产生:

    Text1 
    
    +0

    您的解决方案是否以任何方式优于''? – Borodin 2013-04-22 00:14:13

    +0

    @Borodin,是的。尽管两个XPath表达式在XSLT 1.0/XPath 1.0中是相同的,但它们在XSLT 2.0/XPath 2.0中有不同的结果。我的答案中的XPath表达式在XSLT 1.0和XSLT 2.0中都产生了正确的结果。它具有清楚显示将输出多个可能选择的节点中的哪一个的附加值。 – 2013-04-22 00:17:50

    相关问题