简体   繁体   中英

How to get text without child nodes in XSLT?

I have the following XML

<title>Products</title>
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="products.xsd">
  <product>
    The product called <name>Lorem</name> is available for <price>€ 80</price> only.
  </product>
</products>

Now I want to format the XML above. The name should have, for instance, a red color and the price should be blue.

I have tried the following:

<xsl:for-each select="products/product">
      <div>
        <p style="font-weight:bold">
          <xsl:value-of select="text()"/>
          <span style="color:red"><xsl:value-of select="name"/></span>
          <span style="color:blue"><xsl:value-of select="price"/></span>
        </p>
      </div>
</xsl:for-each>

But this doesn't work at all...

Also I want to format the title but I am not sure how to get the content in the XSLT file.

I suggest you try a different approach, along the lines of:

<xsl:template match="product">
    <div>
        <p style="font-weight:bold">
            <xsl:apply-templates/>
        </p>
    </div>
</xsl:template>

<xsl:template match="name">
    <span style="color:red">
        <xsl:apply-templates/>
    </span>
</xsl:template> 

<xsl:template match="price">
    <span style="color:blue">
        <xsl:apply-templates/>
    </span>
</xsl:template>

Note that this is incomplete - but so is the the code you have provided.

Also I want to format the title

In the same manner, add a template matching title .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM