使用可扩展样式表语言转换(Extensible Stylesheet Language Transformation(XSLT))通常是将XML 数据从一种形式转换成另一种形式的最方便的方法,勿需多言,看代码吧:
XML 文件:
Code<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xsl" href="XSLTFile.xslt"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <publish_date> <year>2000</year> <month>10</month> <day>1</day> </publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <publish_date> <year>2000</year> <month>12</month> <day>16</day> </publish_date> <description>A former architect battles corporate zombies.</description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <publish_date> <year>2000</year> <month>11</month> <day>17</day> </publish_date> <description>After the collapse of a nanotechnology society in England.</description> </book> </catalog>
XSLT 文件:
Code<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="xs fn"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xsl:for-each select="//book"> <bookDesc> <xsl:value-of select="@id"/> with author <xsl:value-of select="./author"/>; </bookDesc> </xsl:for-each> </xsl:template> </xsl:stylesheet>
效果:
浏览器直接显示:
bk101 with author Gambardella, Matthew; bk102 with author Ralls, Kim; bk103 with author Corets, Eva;