我正在尝试学习XSLT,但我最好通过示例.我想对模式转换执行一个简单的模式.如何仅在一次传递中执行此转换(我当前的解决方案使用两次传递并失去客户的原始订单)?
从:
<?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>
Run Code Online (Sandbox Code Playgroud)
至 :
<?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>
Run Code Online (Sandbox Code Playgroud)
我已经解决了这个坏方法(我失去了客户的顺序,我认为我必须多次解析文件:
<?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> …Run Code Online (Sandbox Code Playgroud) <RowSet>
<Row>
<Location_Long_Desc>Sydney Office</Location_Long_Desc>
<Location_Code>SYDNEY</Location_Code>
<Daypart_Long_Desc>Peak Night</Daypart_Long_Desc>
<Daypart_Code>PEANIG</Daypart_Code>
<W_20050703_Dlr>30849.3</W_20050703_Dlr>
<W_20050703_Spots>9</W_20050703_Spots>
<W_20050710_Dlr>16.35</W_20050710_Dlr>
<W_20050710_Spots>19</W_20050710_Spots>
</Row>
</RowSet>
Run Code Online (Sandbox Code Playgroud)
所以,我现在有了这个XML,我需要将W_节点转换为新的单个节点.使用这个XSL
<?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="node()">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:variable name="tmp" select="local-name()"/>
<xsl:choose>
<xsl:when test="starts-with($tmp, 'W_') and ends-with($tmp, '_Dlr')">
<xsl:if test="text() != ''">
<xsl:element name="Expenditure">
<xsl:element name="Period">
<xsl:value-of select="substring($tmp,3,8)"/>
</xsl:element>
<xsl:element name="Value">
<xsl:apply-templates select="node()"/>
</xsl:element>
<xsl:element name="Spots">
<xsl:apply-templates select="//RowSet/Row/W_20050703_Spots/text()"/>
</xsl:element>
</xsl:element>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:element name="{$tmp}">
<xsl:apply-templates select="node()"/>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
我几乎可以到达那里,但我有几个问题.
xslt ×2