16.3 简要介绍XSLT
这里将开始介绍本章最为复杂的内容。
可扩展样式表语言转换(Extensible Stylesheet Language Transformation,XSLT)使XML有了多种功能。使用XSLT,可以把XML文档转换成其他的形式。
为了快速了解一下这方面的内容,现在来看一下Northwind数据库产生的XML文档。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Customer CustomerID="ALFKI" CompanyName="Alfreds Futterkiste">
<Products ProductID="28" ProductName="Rössle Sauerkraut"/>
<Products ProductID="39" ProductName="Chartreuse verte"/>
<Products ProductID="46" ProductName="Spegesild"/>
</Customer>
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils">
<Products ProductID="28" ProductName="Rössle Sauerkraut"/>
<Products ProductID="29" ProductName="Thüringer Rostbratwurst"/>
<Products ProductID="31" ProductName="Gorgonzola Telino"/>
<Products ProductID="38" ProductName="Côte de Blaye"/>
<Products ProductID="39" ProductName="Chartreuse verte"/>
<Products ProductID="41" ProductName="Jack's New England Clam
Chowder"/>
<Products ProductID="46" ProductName="Spegesild"/>
<Products ProductID="49" ProductName="Maxilaku"/>
</Customer>
</root>
这里得到的是XML的层次结构。在本例中,会碰到客户订购不同产品的情况。XML文档告诉了我们客户所购买的物品。这看上去很合理,不是吗?
这里对它作些修改——如果问题是“订购每件物品的客户是谁?”那该怎么办呢?我们的观点将大为改变。这里会有一个更好的层次结构,其中产品在外层,而客户在内层。在该场景中,客户(而不是产品)会多次地出现(一次对应一个产品),但是对根的访问将会更多。
将XML与XSL转换相结合是很正常的。可以看到,不用去修改数据的外观——只要转换XML文档,这样结构就会不一样。
提示:
不要以为上面说的“数据的外观”是指视觉上看到的情况—— 而是指如何去理解该数据。其中一部分是指如何根据特殊的方式使用数据。当客户在层次结构的顶层时,数据将不能很好地回答以产品为中心的问题。这里需要将数据转换为以产品为中心,就像前面的那个问题一样。
下面看一下有着相同的数据、但是以另一种样式表示的XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Products ProductID="28" ProductName="Rössle Sauerkraut">
<Customer CustomerID="ALFKI" CompanyName="Alfreds Futterkiste"/>
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="29" ProductName="Thüringer Rostbratwurst">
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="31" ProductName="Gorgonzola Telino">
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="38" ProductName="Côte de Blaye">
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="39" ProductName="Chartreuse verte">
<Customer CustomerID="ALFKI" CompanyName="Alfreds Futterkiste"/>
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="41" ProductName="Jack's New England Clam Chowder">
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="46" ProductName="Spegesild">
<Customer CustomerID="ALFKI" CompanyName="Alfreds Futterkiste"/>
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
<Products ProductID="49" ProductName="Maxilaku">
<Customer CustomerID="BLONP" CompanyName="Blondesddsl père et fils"/>
</Products>
</root>
同样,这是相同的数据——只是观点不同而已。
为什么要限于XML呢?对每一种转换类型的介绍超出了本书的范围,但是理解XSL可以用很多种格式进行转换,这一点很重要。可以把它转化为其他XML的布局,也可以把它全部转换成其他的格式,如CSV文件或者Word文档。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1583566