Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to XSLT pattern doesn't match

Tags:

xml

xslt

xslt-1.0

I am playing around with XSLT for a small task. I have the following XML:

 <PFeed>
  <PID> MyProcess </PID>
  <Version>1</Version>
  <MetaData>
      <Id> MyMetadataId </Id>
  </MetaData>
 <AllFeeds>
   <FeedContent>
      <Id> FeedContentId </Id>
   </FeedContent>
 </AllFeeds>
</PFeed>

I want to extract FeedContentId as text from this XML.

This is the XSLT code I have:

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
  <xsl:output method="text" encoding="UTF-8" />
  <xsl:template match="/PFeed/AllFeeds/FeedContent">
        <xsl:value-of select="Id"/>
  </xsl:template>
</xsl:stylesheet>

But instead of outputting FeedContentId I get the following: MyProcess 1 MyMetadataId FeedContentId

Can you please point out what I am missing ?

like image 208
goutham_kgh Avatar asked Dec 03 '25 15:12

goutham_kgh


1 Answers

You first need a template to match the root element, then match what's inside. This XSLT now works again. (Test e.g. on http://www.w3schools.com/xsl/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog)

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="text" indent="yes" omit-xml-declaration="yes" />

  <xsl:template match="/PFeed">
    <xsl:apply-templates select="AllFeeds/FeedContent"/>
  </xsl:template>

  <xsl:template match="FeedContent">
      <xsl:value-of select="Id"/>
  </xsl:template>
</xsl:stylesheet>

Output after transformation:

FeedContentId

However, the same thing (getting the /PFeed/AllFeeds/FeedContent/Id node) could also be achieved by evaluating the above simple XPath expression.

like image 127
Maximilian Gerhardt Avatar answered Dec 06 '25 10:12

Maximilian Gerhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!