【问题标题】:how to output text inside an xml tag using xslt如何使用 xslt 在 xml 标签内输出文本
【发布时间】:2014-08-07 18:19:04
【问题描述】:

我有一个 xml 文件,其中的场景是这样的

<heading inline='true'>
 HELLO
</heading>
  <abc>
     <p>WORLD</p>
     <p>NEW LINE1</p>
     <p>NEW LINE2</p>
     <p>NEW LINE3</p>
  </abc>

我需要输出

HELLO WORLD$TNEW LINE1$TNEW LINE2$TNEW LINE3

使用 xslt。

规则是,如果 p 标签之前有一个内联属性为 true 的标题标签,则第一个 p 标签需要输出一个空格,其余所有 p 标签都需要输出 $T。

我尝试过的:-

<xsl:template match="p">
<xsl:choose>
 <xsl:when test="preceding::heading[@isInline= 'true'] and not(preceding::p)"> 
  <xsl:text> </xsl:text>
  <xsl:when>

  <xsl:otherwise>
   <xsl:text>$T</xsl:text>
  </xsl:otherwise>
    </xsl:choose>

<xsl:apply-templates/>
</xsl:template>

但是 p 前面有很多标题标签,我的 sn-p 占了 p 前面的所有标题标签。我想考虑 p 之前的标题标签 just。 标签中也可以有很多级别的嵌套,我不能使用涉及 abc 和兄弟的相对 xpath

我使用的是 xslt 2.0,输出方法是文本

任何输入都会有很大帮助

【问题讨论】:

  • 密钥是&lt;xsl:when test="preceding::*[1][name()='heading'][@inline= 'true']"&gt;。请看我的回答。

标签: xml xslt text xpath


【解决方案1】:

试试下面的样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:strip-space elements="*"/>

    <xsl:output method="text"/>

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

    <xsl:template match="p">
        <xsl:choose>
            <!-- test for the first preceding node named heading, with an inline attribute equal to true -->
            <xsl:when test="preceding::*[1][name()='heading'][@inline= 'true']">
                <xsl:text> </xsl:text>
            </xsl:when>
            <xsl:otherwise>
                <xsl:text>$T</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:apply-templates/>
    </xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多