将XML格式转换为另一种格式

时间:2018-03-11 01:16:15

标签: xml xslt xslt-1.0

我需要将消息数据从一种格式转换为另一种格式。原始文件有3472个条目(短信/短信)。不再需要id,threadId,person。但我必须创建@time,@ name。

我的格式:

<?xml version='1.0' encoding='UTF-8'?>
<smsall>
  <sms>
    <id>200</id>
    <threadId>65</threadId>
    <address>+123456789</address>
    <person>1</person>
    <date>1387977340608</date>
    <body> This is a text </body>
    <type>1</type>
    <read>1</read>
  </sms>
</smsall>

运行XSLT 1.0后我需要的格式:

<?xml version="1.0" encoding="UTF-8"?>
<allsms count="1">
  <sms address="+123456789" time="" date="1387977340608" type="1" body="This is a text" read="1" service_center="" name="" />
</allsms>

我花了很多天但我却悲惨地失败了。请有人帮帮我吗?

1 个答案:

答案 0 :(得分:0)

问题并不复杂,但你必须记住两个细节:

首先: XSLT 1.0 xsl:attribute的语法不允许select属性。相反,您必须使用此标记的内容,例如:

 <xsl:attribute name="address">
   <xsl:value-of select="address"/>
 </xsl:attribute>

第二种:要拥有一个带有内容的属性,就足够了 仅将xsl:attribute名称放在一起,但没有任何内容,例如:

<xsl:attribute name="time"/>

所以脚本如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes" />

  <xsl:template match="smsall">
    <allsms>
      <xsl:attribute name="count">
        <xsl:value-of select="count(sms)"/>
      </xsl:attribute>
      <xsl:apply-templates/>
    </allsms>
  </xsl:template>

  <xsl:template match="sms">
    <sms>
      <xsl:attribute name="address">
        <xsl:value-of select="address"/>
      </xsl:attribute>
      <xsl:attribute name="time"/>
      <xsl:attribute name="date">
        <xsl:value-of select="date"/>
      </xsl:attribute>
      <xsl:attribute name="type">
        <xsl:value-of select="type"/>
      </xsl:attribute>
      <xsl:attribute name="body">
        <xsl:value-of select="normalize-space(body)"/>
      </xsl:attribute>
      <xsl:attribute name="read">
        <xsl:value-of select="read"/>
      </xsl:attribute>
      <xsl:attribute name="service_center"/>
      <xsl:attribute name="name"/>
    </sms>
  </xsl:template>
</xsl:stylesheet>

有关工作示例(在 XSLT 1.0 中),请参阅http://xsltransform.net/nb9MWsZ

相关问题