使用XSLT使用源XML中的数据作为元素名称在目标XML中创建元素

时间:2013-11-19 23:10:26

标签: xml xslt

我的源XML包含数据和“元数据”,用于描述目标XML 源数据是条目(字段)的通用集合,我的目标是创建具有特定标记名称的XML 是否可以使用XSLT将下面的源转换为目标?

来源:

<section>
   <name>TaxpayerInfo</name>
   <field>
       <name>firstName</name>
       <value>John</value>
  </field>
  <field>
       <name>lastName</name>
       <value>Smith</value>
  </field>
 </section>

:定位

 <taxpayerInfo>   
   <firstName>John</firstName>    
   <lastName>Smith</lastName> 
 </taxpayerInfo>

2 个答案:

答案 0 :(得分:1)

您可以尝试以下XSLT(1.0)。

假设原始文档中的“section”元素将是您想要的元素的定义。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="section">
    <xsl:variable name="fieldName" select="name" />

    <xsl:element name="{$fieldName}">
      <xsl:apply-templates select="field"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="field">
    <xsl:variable name="fieldName" select="name" />
    <xsl:element name="{$fieldName}">
      <xsl:value-of select="value"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

对你的示例XML使用这个xslt给了我以下结果

<?xml version="1.0" encoding="utf-8"?>
<TaxpayerInfo>
  <firstName>John</firstName>
  <lastName>Smith</lastName>
</TaxpayerInfo>

希望这有帮助,

答案 1 :(得分:0)

尝试一下:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <xsl:element name="taxpayerInfo">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="section">
        <xsl:apply-templates/>
    </xsl:template>
    <xsl:template match="field[position() = 1]">
        <xsl:element name="firstName">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="field[position() = 2]">
        <xsl:element name="lastName">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="name"/>
</xsl:stylesheet>