XSLT简单转换

时间:2015-01-14 20:43:34

标签: xml xslt

我有一个非常简单的任务,但我被困在这里。

所以,我有这样的XML文件:

<entries>
<entry>
    <field>field value</field>
</entry>
...
<entry>
    <field>field value</field>
</entry>

它应该用XSLT进行转换,看起来像这样:

<entries>
<entry field="field value">
...
<entry field="field value">
</entries>

你能用模板帮我吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

这可以通过以下XSLT完成:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" 
    indent="yes" />
<xsl:strip-space elements="*"/>
  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="entry">
    <xsl:copy>
        <xsl:attribute name="field">
          <xsl:value-of select="field"/>
        </xsl:attribute> 
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="field"/>
</xsl:transform>

应用于示例输入XML

<entries>
  <entry>
    <field>field value 1</field>
  </entry>
  <entry>
    <field>field value 2</field>
  </entry>
</entries>

生成以下输出:

<entries>
 <entry field="field value 1"/>
 <entry field="field value 2"/>
</entries>

匹配entry <xsl:template match="entry">

的模板

复制entry并将属性field添加为field节点的值:

<xsl:copy>
  <xsl:attribute name="field">
    <xsl:value-of select="field"/>
  </xsl:attribute> 
  <xsl:apply-templates/>
</xsl:copy>

且匹配field <xsl:template match="field"/>的模板为空,并删除field个节点。