Stephen Palfreyman
Stephen Palfreyman

Reputation: 123

An attribute node cannot be created after the children of the containing element

I have a simple XML file for which I need to update an attribute value (should be simple enough). Despite copying other examples that do work, I am getting the error "An attribute node (LastUpdateDate) cannot be created after the children of the containing element". Can anyone spot what I am doing wrong or suggest an alternative approach?

My XML is:

<Root>
  <Datasource Name="SCV">
    <Datafeed FeedMask="yyyyMMdd_Individual" LastUpdateDate="20140401"/>
    <Datafeed FeedMask="yyyyMMdd_MarketingPreferences" LastUpdateDate="20140401"/>
  </Datasource>
</Root>

My XSL is:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="/Root/Datasource[@Name='SCV']/Datafeed[@FeedMask='yyyyMMdd_Individual']">
    <xsl:attribute name="LastUpdateDate"><xsl:value-of select="20140402"/> </xsl:attribute>
  </xsl:template>
</xsl:transform>

Thanks for your help,

Steve

Upvotes: 2

Views: 7910

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116982

You need to copy the element before you can add an attribute to it:

<xsl:template match="/Root/Datasource[@Name='SCV']/Datafeed[@FeedMask='yyyyMMdd_Individual']">
    <xsl:copy>
        <xsl:attribute name="LastUpdateDate">
            <xsl:value-of select="20140402"/>
        </xsl:attribute>
    </xsl:copy>
</xsl:template>

Note that if the attribute already exist, and you only want to modify it, you can have the template match the attribute directly:

<xsl:template match="/Root/Datasource[@Name='SCV']/Datafeed[@FeedMask='yyyyMMdd_Individual']/@LastUpdateDate">
    <xsl:attribute name="LastUpdateDate">
        <xsl:value-of select="20140402"/>
    </xsl:attribute>
</xsl:template>

Upvotes: 3

Related Questions