XSLT:将xml内容拆分为单独的元素

时间:2013-12-26 04:25:21

标签: xml xslt

我有以下xml。

 <?xml version="1.0"?>
    <?xml-stylesheet type="text/xsl" href="applyt.xsl" ?>
    <customers>
      <order>
        <id>1</id>
        <name>John</name>
        <customerBlkNo>178</customerBlkNo>
        <CustomerStreetNo>xyz Avenue 1</CustomerStreetNo>
        <CustomerCountry>China</CustomerCountry>
        <phone>123-4567</phone>
       </order>
    </customers>

我需要转换这个xml,如下所示。

 <customers>
      <order>
        <id>1</id>
        <name>John</name>
        <customeraddress>
          <BlkNo>178</BlkNo>
          <StreetNo>xyz Avenue 1</StreetNo>
          <Country>China</Country>
        </customeraddress>
        <phone>123-4567</phone>
       </order>
  </customers>

我是xslt的新手。请有人帮助我。谢谢你提前

1 个答案:

答案 0 :(得分:0)

因为XSLT非常有趣,所以这里有一个工作样式表来总结客户地址。它使用XSLT 2.0,因为您没有说明您要使用哪个版本。

<强>样式表

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="customers|order|id|name|phone">
  <xsl:copy>
     <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="customerBlkNo">
  <customeraddress>
     <BlkNo>
        <xsl:value-of select="."/>
     </BlkNo>
     <StreetNo>
        <xsl:value-of select="../CustomerStreetNo"/>
     </StreetNo>
     <Country>
        <xsl:value-of select="../CustomerCountry"/>
     </Country>
  </customeraddress>
</xsl:template>

<xsl:template match="CustomerStreetNo|CustomerCountry"/>

</xsl:stylesheet>

<强>输出

<?xml version="1.0" encoding="UTF-8"?>
<customers>
 <order>
  <id>1</id>
  <name>John</name>
  <customeraddress>
     <BlkNo>178</BlkNo>
     <StreetNo>xyz Avenue 1</StreetNo>
     <Country>China</Country>
  </customeraddress>
  <phone>123-4567</phone>
 </order>
</customers>