我正在尝试学习 XSLT,但通过示例效果最好。我想执行一个简单的模式到模式转换。如何仅通过一次传递来执行此转换(我当前的解决方案使用两次传递并丢失客户的原始订单)?
From:
<?xml version="1.0" encoding="UTF-8"?>
<sampleroot>
<badcustomer>
<name>Donald</name>
<address>Hong Kong</address>
<age>72</age>
</badcustomer>
<goodcustomer>
<name>Jim</name>
<address>Wales</address>
<age>22</age>
</goodcustomer>
<goodcustomer>
<name>Albert</name>
<address>France</address>
<age>51</age>
</goodcustomer>
</sampleroot>
To :
<?xml version="1.0" encoding="UTF-8"?>
<records>
<record id="customer">
<name>Donald</name>
<address>Hong Kong</address>
<age>72</age>
<customertype>bad</customertype>
</record>
<record id="customer">
<name>Jim</name>
<address>Wales</address>
<age>22</age>
<customertype>good</customertype>
</record>
<record id="customer">
<name>Albert</name>
<address>France</address>
<age>51</age>
<customertype>good</customertype>
</record>
</records>
我已经解决了这个问题bad方式(我失去了客户的订单,我认为我必须多次解析文件:
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/sampleroot">
<records>
<xsl:for-each select="goodcustomer">
<record id="customer">
<name><xsl:value-of select="name" /></name>
<address><xsl:value-of select="address" /></address>
<age><xsl:value-of select="age" /></age>
<customertype>good</customertype>
</record>
</xsl:for-each>
<xsl:for-each select="badcustomer">
<record id="customer">
<name><xsl:value-of select="name" /></name>
<address><xsl:value-of select="address" /></address>
<age><xsl:value-of select="age" /></age>
<customertype>bad</customertype>
</record>
</xsl:for-each>
</records>
</xsl:template>
</xsl:stylesheet>
请问有人可以帮助我使用正确的 XSLT 构造吗?我只需使用一次解析(每个解析只需一个)?
Thanks,
Chris
避免使用 XSLT 是一个很好的做法<xsl:for-each>
越多越好.
这是一个简单的解决方案,利用这个原理:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<records>
<xsl:apply-templates/>
</records>
</xsl:template>
<xsl:template match="badcustomer | goodcustomer">
<record>
<xsl:apply-templates/>
<customertype>
<xsl:value-of select="substring-before(name(), 'customer')"/>
</customertype>
</record>
</xsl:template>
</xsl:stylesheet>
Do note:
仅模板和<xsl:apply-templates>
被使用。
在必要时使用身份规则并覆盖它。这是最基本的 XSLT 设计模式之一。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)