views:

92

answers:

2

How to copy data of attribute to new attribute in the same column in sql

original data

<root>
<child attr='hello'></child>
</root>

Result 1

<root>
<child attr='hello' attr2='hello'></child>
</root>

Result 2(with a modification)

<root>
<child attr='hello' attr2='**H**ello **W**orld'></child>
</root>

I want to do this only through SQL XML Xquery

A: 

Assuming that we can use XSLT, I would do it like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output method="xml" indent="yes" omit-xml-declaration="no" />

    <xsl:template match="root">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="child">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:attribute name="attr2">
                <xsl:value-of select="@attr"/>
            </xsl:attribute>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet> 

Or, if you want the modification in Result 2, replace <xsl:template match="child"> with the following:

<xsl:template match="child">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="attr2">
            <xsl:value-of>
                <xsl:text>**H**ello **W**orld</xsl:text>
            </xsl:value-of>
        </xsl:attribute>
    </xsl:copy>
</xsl:template>
MarcoS
I want to do this only through SQL XML Xquery
Mukesh
A: 

I'm not sure I follow what you're wanting exactly in the second result, but I'll take a stab at it: the first example below would produce your result #1 (I've put your original data in test.xml and assumed in your real data that 'child' and 'attr' might be repeated):

<root>{
  for $child in doc('test.xml')/root/*
  return
    element {name($child)} {
      for $attr at $index in $child/@*
      return (
        attribute {name($attr)} {$attr},
        attribute {concat(name($attr), 2)} {$attr}
      )
    }
}</root>

It could be modified to put a different value in, like in result #2, like the below:

<root>{
  for $child in doc('test.xml')/root/*
  return
    element {name($child)} {
      for $attr at $index in $child/@*
      return (
        attribute {name($attr)} {$attr},
        attribute {concat(name($attr), 2)} {
          '**H**ello **W**orld' 
        }
      )
    }
}</root>

Hope that helps.

ksclarke
I want to do this only through SQL XML Xquery
Mukesh