我有这个类型的XML文件(test.xml):
<product>
<node>
<region_id>
<node>1</node>
</region_id>
<region_time>
<node>27</node>
<node>02</node>
<node>2013</node>
</region_time>
<tab_id>351</tab_id>
<product_id>1</product_id>
<tab_name>test1</tab_name>
</node>
</product>
我想把它们改成像这样的类型:
<product>
<region_id>1</region_id>
<region_time>27,02,2013</region_time>
<tab_id value="351"></tab_id>
<product_id value="1"></product_id>
<tab_name value="test1"></tab_name>
</product>
这里我使用XSLT
PHP
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<!-- from dimitre's xsl.thanks -->
<xsl:template match="node[position()>1]/text()">
<xsl:text>,</xsl:text>
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>
xslt.php
$sourcedoc = new DOMDocument();
$sourcedoc->load('test.xml');
$stylesheet = new DOMDocument();
$stylesheet->load('test.xsl');
// create a new XSLT processor and load the stylesheet
$xsltprocessor = new XSLTProcessor();
$xsltprocessor->importStylesheet($stylesheet);
// save the new xml file
file_put_contents('test-translated.xml', $xsltprocessor->transformToXML($sourcedoc));
在此代码下,O/p为:
<product>
<region_id>1</region_id>
<region_time>27,02,2013</region_time>
</tab_id>
</product_id>
</tab_name>
</product>
不给<tab_id> <product_id>
和<tab_name>
谢谢. .
像这样添加一个<xsl:template>
元素应该可以达到这个效果:
<xsl:template match="tab_id | product_id | tab_name">
<xsl:copy>
<xsl:attribute name="value">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:copy>
</xsl:template>