Dessoul
Dessoul

Reputation: 35

XML change tag name with tag content

I have a XML file which look like this :

<MyObject>
    <ID>1</ID>
    <Name>Foo</Name1>
    <Color>Blue</Color>
    ...
    <CustomFields>
        <CustomField>
            <Name>cf1</Name>
            <Type>boolean</Type>
            <Value>true</Value>
        </CustomField>
        <CustomField>
            <Name>cf2</Name>
            <Type>interger</Type>
            <Value>1</Value>
        </CustomField>
        ...
    </CustomFields>
</MyObject>

The problem is that when I import it in Excel for example, Excel creates me 2 lines :

ID , Name , Color , CustomField/Name , CustomField/Type , CustomField/Value
1 , Foo , Blue , cf1 , boolean , true
1 , Foo , Blue , cf2 , integer, 1

I would rather like to have unique columns per custom fields. So my idea was to transform the source XML by changing the "CustomField" (without "s") tag name, to make it unique. I thought to concatenate "CustomField" with the "Name" tag content.

So, I will transform

<CustomField>
    <Name>cf1</Name>
    <Type>boolean</Type>
    <Value>true</Value>
</CustomField>
<CustomField>
    <Name>cf2</Name>
    <Type>interger</Type>
    <Value>1</Value>
</CustomField>

Into

<CustomField_cf1>
    <Name>cf1</Name>
    <Type>boolean</Type>
    <Value>true</Value>
</CustomField_cf1>
<CustomField_cf2>
    <Name>cf2</Name>
    <Type>interger</Type>
    <Value>1</Value>
</CustomField_cf2>

The problem is that I have no idea how to change some chosen tag name with the value of a sub-node.

I looked into XSLT but clearly I do not have the required level to do such thing. So I am open to any kind of solution.

Thx

Upvotes: 2

Views: 913

Answers (2)

ScanQR
ScanQR

Reputation: 3820

Try this,

I have added relevant transformation that you required.

http://xsltransform.net/ejivdHb/13

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167506

Use the identity transformation template plus a template

<xsl:template match="CustomField">
  <xsl:element name="{name()}_{Name}">
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>

Upvotes: 0

Related Questions