user1472409
user1472409

Reputation: 407

Add XML Attribute Using XSLT

I am currently using an XSLT to pull values out of an XML document and create a new XML document. Part of my XSLT is below:

<xsl:element name="urn:sObjects">
    <xsl:element name="urn1:type">
          <xsl:value-of select="/ProcessData/Create/type"/>
    </xsl:element>
    <xsl:element name="CreatedDate">
          <xsl:value-of select="Create/CreatedDate"/>
    </xsl:element>
    <xsl:element name="Alert_Code__c">
          <xsl:value-of select="Create/AlertCode"/>
    </xsl:element>
    <xsl:element name="Status__c">
          <xsl:value-of select="Create/Status"/>
    </xsl:element>
    <xsl:element name="Name">
          <xsl:value-of select="Create/Name"/>
    </xsl:element>
    <xsl:element name="Order_Id__c">
          <xsl:value-of select="Create/OrderID"/>
    </xsl:element>
</xsl:element>

Currently, this outputs:

<urn:sObjects>
  <urn1:type xmlns:urn1="urn:sobject.enterprise.soap.sforce.com">O2C_SAP_Service_Alert__c</urn1:type>
  <CreatedDate />
  <Alert_Code__c>ZD</Alert_Code__c>
  <Status__c>new</Status__c>
  <Name />
  <Order_Id__c>0000000102</Order_Id__c>
</urn:sObjects>

What I would like it to output is:

<urn:sObjects xsi:type="urn1:O2C_Alert__c">
  <urn1:type xmlns:urn1="urn:sobject.enterprise.soap.sforce.com">O2C_SAP_Service_Alert__c</urn1:type>
  <CreatedDate />
  <Alert_Code__c>ZD</Alert_Code__c>
  <Status__c>new</Status__c>
  <Name />
  <Order_Id__c>0000000102</Order_Id__c>
</urn:sObjects>

In other words, I would like to add the attribute xsi:type="urn1:O2C_Alert__c" to this XML message.

How could I do that, using the XSLT?

Upvotes: 1

Views: 143

Answers (1)

Linga Murthy C S
Linga Murthy C S

Reputation: 5432

You needn't use xsl:element to create an element. You can simplify it to the following (make sure that there is a namespace declared for xsi prefix):

<urn:sObjects xsi:type="urn1:O2C_Alert__c">
    <urn1:type>
        <xsl:value-of select="/ProcessData/Create/type"/>
    </urn1:type>
</urn:sObjects>

EDIT: To make the attribute value dynamic, you can use {} to evaluate an xpath as following:

<urn:sObjects xsi:type="{a/b/c}">

Or, you can use:

<urn:sObjects>
    <xsl:attribute name="xsi:type">
        <xsl:value-of select="a/b/c"/>
    </xsl:attribute>
    <!-- followed by other attributes, and then by elements -->
</urn:sObjects>

Make sure that all xsl:attribute are declared before any child elements.

Upvotes: 3

Related Questions