Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

xml - XSLT Transform doesn't work until I remove root node

I'm trying to extract the headline from the below XML from the Met Office web service using XSLT, however my XSLT select returns blank.

SOURCE:

<RegionalFcst xmlns="www.metoffice.gov.uk/xml/metoRegionalFcst" createdOn="2016-01-13T02:14:39" issuedAt="2016-01-13T04:00:00" regionId="se">
 <FcstPeriods>
  <Period id="day1to2">
   <Paragraph title="Headline:">Frosty start. Bright or sunny day.</Paragraph>
   <Paragraph title="Today:">A clear and frosty start in west, but cloudier in Kent with isolated showers. Then dry with sunny periods. Increasing cloud in west later will bring coastal showers with freshening southerly winds. Chilly inland, but less cold near coasts. Maximum Temperature 8C.</Paragraph>
  </Period>
 </FcstPeriods>
</RegionalFcst>

My XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
   <xsl:value-of select="FcstPeriods/Period/Paragraph"/>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

I've changed the root to /RegionalFcst and attempted other similar changes, such as adding a leading slash before FcstPeriods, but nothing works until I remove the first and last line from the source XML - then it works perfectly.

This is fine in testing, but of course I want to use the web service provided by Met Office and that's how they present it.

Any ideas?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem: your XML puts its elements in a namespace.

Solution: declare the same namespace in your stylesheet, assign it a prefix and use that prefix to address the elements in the source XML:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:met="www.metoffice.gov.uk/xml/metoRegionalFcst"
exclude-result-prefixes="met">
<xsl:template match="/">
  <html>
  <body>
   <xsl:value-of select="met:RegionalFcst/met:FcstPeriods/met:Period/met:Paragraph[@title='Headline:']"/>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...