使用xslt创建动态xml元素

时间:2016-08-19 06:18:05

标签: xml xslt dynamic xsd xslt-grouping

我正在使用XSLT来传输xml对象值,这是我对此技术的新手,基于我需要为输出创建xml元素的值。请帮帮我,

以下是我的要求

输入xml

<list>
    <creature>
        <type>Animal</type>
        <explicit-path>
            <name>AnimalName</name>
            <constraints>
                <nd-ref>fourlegs</nd-ref>
                <interface>runs</interface>
            </constraints>
        </explicit-path>
    </creature>
<creature>
        <type>Bird</type>
        <explicit-path>
            <name>BirdName</name>
            <constraints>
                <nd-ref>twolegs</nd-ref>
                <interface>flies</interface>
            </constraints>
        </explicit-path>    
    </creature>     
</list>
  • 预期输出

    <Animal>
    <name>animalName</name>
    <constraints>
        <nd-ref>fourlegs</nd-ref>
        <interface>runs</interface>
    </constraints>
    </Animal>
    <Bird>
    <name>birdName</name>
    <constraints>
        <nd-ref>twolegs</nd-ref>
        <interface>flies</interface>
    </constraints>
    </Bird>
    

2 个答案:

答案 0 :(得分:0)

试试这个:

XSLT 2.0:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

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

<xsl:template match="list">
    <xsl:copy>
        <xsl:for-each select="creature">
            <xsl:element name="{type}">
                <xsl:apply-templates select="explicit-path/*"/>
            </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

<强>输出:

<list>
<Animal>
  <name>AnimalName</name>
  <constraints>
     <nd-ref>fourlegs</nd-ref>
     <interface>runs</interface>
  </constraints>
</Animal>
<Bird>
  <name>BirdName</name>
  <constraints>
     <nd-ref>twolegs</nd-ref>
     <interface>flies</interface>
  </constraints>
</Bird>
</list>

答案 1 :(得分:0)

您可以尝试这个更简单的样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

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

    <xsl:template match="/">
        <xsl:for-each select="list/creature">
            <xsl:element name="{type}">
                <!-- copy exactly the elements under explicit-path -->
                <xsl:copy-of select="explicit-path/*"/>
            </xsl:element>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>
相关问题