转换xml文件

时间:2011-05-09 01:43:43

标签: php xml xslt

如何使用a在products.xml上执行服务器端转换 XSLT样式表。结果将是具有以下结构的XML文件(item.xml)  其中ocshelf =“是”和type =“cosmetic”

products.xml ------------------------

<products>
<product onshelf=“yes” condition=“ok”>
<type>cosmetic</type>
<price>680</price>
<address>
<streetNo>1</streetNo>
<street>Jefer Street</street>
<suburb>Melbourne</suburb>
</address>
</product>
<product onshelf=“yes” condition=“ok”>
<type>noncosmetic</type>
<price>600</price>
<address>
<streetNo>2</streetNo>
<street>Colo Street</street>
<suburb>Melbourne</suburb>
</address>
</product>
</products>

item.xml ---------------------------------

<products>
<product condition=“ok”>
<type>cosmetic</type>
<price>680</price>
<address>1 Jefer Street , Melbourne </address>
</product>
</products>

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema" 
                exclude-result-prefixes="xs" 
                version="2.0">
    <xsl:template match="/">
        <products>
            <xsl:apply-templates 
                select="/products/product[@onshelf='yes' and type='cosmetic']"/>
        </products>
    </xsl:template>
    <xsl:template match="product">
        <product condition="{@condition}">
            <xsl:apply-templates />
        </product>
    </xsl:template>
    <xsl:template match="address">
        <address>
            <xsl:value-of select="concat(streetNo, ' ', street, ', ', suburb)" />
        </address>
    </xsl:template>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

如果您不熟悉XSLT,我建议您查看此主题以获取教程建议:https://stackoverflow.com/questions/1858345/xsltwhich-is-the-best-tutorial-you-would-like-to-recommend