Search code examples
xmlxsltumlxmi

XMI to XML by using XSLT


Please i'm beginner in XSLT. Can some one explain for me how transform this XMI file to XML file ?

<?xml version="1.0" encoding="UTF-8"?>
<projet:Config xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:test="http://projet.org/test" xmlns:occi="http://schemas.ogf.org/projet">
<use href="extensions/plugin.xmi#/"/>

<group id="group1">
    <type href="extensions/plugin#//[term='host']"/>
    <variable name="v1" value="x86"/>
    <variable name="v2"  value="Linux"/>
    <variable name="v3"  value="Xen"/>  
</group>

</projet:Config>

to tansform the previous XMI to xml file such as:

<host v1="x86" v2="Linux" v3="Xen">

Solution

  • There are many many ways to do this. Here's one: Start with a template to match the root node to give you a valid root tag (this is assuming your group nodes are repeatable); have a template below that which matches the group nodes, and a template below that that matches the variable nodes in that group. Build your attributes in the variable template.

    Note that your input XML is invalid and may cause problems - that projet prefix is undeclared, which is why I'm referencing it using the local-name() syntax.

    <?xml version="1.0" encoding="UTF-8" ?>
    <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
        <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
    
        <xsl:template match="/">
            <root>
                <xsl:apply-templates />
            </root>
        </xsl:template>
    
        <xsl:template match="/*[local-name()='Config']/group">
           <xsl:element name="{type/substring-before(substring-after(@href,'term='''), ''']')}">
              <xsl:apply-templates />
          </xsl:element>
        </xsl:template>
    
        <xsl:template match="variable">
            <xsl:attribute name="{@name}"><xsl:value-of select="@value" /></xsl:attribute>
        </xsl:template>
    
    
        <xsl:template match="text()" />
    </xsl:transform>