Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xml

xslt

xpath

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.

like image 934
Saravanan Avatar asked Aug 01 '11 06:08

Saravanan


People also ask

Which XSLT element extracts the value of a selected node?

The <xsl:value-of> element is used to extract the value of a selected node.

Which XSLT element defines a named set of attributes?

The <xsl:attribute-set> element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in CSS.

Which xsl:element is used to extract information from XML document?

The XSLT <xsl:value-of> element is used to extract the value of selected node. It puts the value of selected node as per XPath expression, as text.

What is current group () in XSLT?

Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*


1 Answers

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.

like image 193
Tim C Avatar answered Oct 07 '22 01:10

Tim C