Alex Rivera | Logout

How to select xml element based on its attribute value start with "Heading" in xslt?

Asked 2011-08-01T06:50:14.490
9

I want to call my own xsl template whenever i found the matching of xml element that having its attribute value starting with "Heading". How do I make this query in Xslt.

For example:

<w:p>
  <w:pPr>
     <w:pStyle w:val="Heading2"/>
  </w:pPr>
</w:p>

<w:p>
  <w:pPr>
     <w:pStyle w:val="Heading1"/>
  </w:pPr>
</w:p>

<w:p>
  <w:pPr>
     <w:pStyle w:val="Heading2"/>
  </w:pPr>
</w:p>

<w:p>
  <w:pPr>
     <w:pStyle w:val="ListParagraph"/>
  </w:pPr>
</w:p>

<w:p>
  <w:pPr>
     <w:pStyle w:val="commentText"/>
  </w:pPr>
</w:p>

So, I want to make query that w:pStyle -> w:val starting with "Heading" only.

Edit
Report

1 Answer

16

You can achieve this by making use of the XPath string function starts with

<xsl:template match="w:pStyle[starts-with(@w:val, 'Heading')]">

This simply matches all w:pStyle nodes where the w:val attributes starts with the word Heading. You can then put your own code in this template.

Here is an example of how you would use it in the XSLT identity transform

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:w="http://mynamespace.com">
   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="w:pStyle[starts-with(@w:val, 'Heading')]">
      <!-- Your code here -->
   </xsl:template>

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

The above XSLT, unless you did add you own code where it says, would strip out all mathcing w:pStyle elements from the XML.

answered 2011-08-01T08:00:08.803

Your Answer