如何在新属性中复制属性值

时间:2010-04-09 06:42:12

标签: xml xpath xquery sqlxml

如何在sql

的同一列中将属性数据复制到新属性

原始数据

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

结果1

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

结果2(带修改)

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

我只想通过SQL XML Xquery

执行此操作

3 个答案:

答案 0 :(得分:1)

我不确定我是否会在第二个结果中完全按照您的要求进行操作,但我会抓住它:下面的第一个示例会产生您的结果#1(我已将您的原始数据放入test.xml并在您的真实数据中假设'child'和'attr'可能会重复出现):

<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>

可以修改它以输入不同的值,如结果#2,如下所示:

<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>

希望有所帮助。

答案 1 :(得分:0)

假设我们可以使用XSLT,我会这样做:

<?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> 

或者,如果您想要在结果2中进行修改,请将<xsl:template match="child">替换为以下内容:

<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>

答案 2 :(得分:0)

DECLARE @xmlData table (
   data xml
   )


INSERT INTO @xmlData(data) 
VALUES ('<root>
   <child attr="hello"></child>
   </root>')

.modify() performs all operations

UPDATE @xmlData
SET data.modify('insert (attribute attr2 {"hello"}) into (/root/child)[1]')

Verify that the data is correct

SELECT *
FROM @xmlData


UPDATE @xmlData
SET data.modify('replace value of (/root/child/@attr2)[1] with "**H**ello **W**orld" ')

Verify that the data is correct

SELECT *
FROM @xmlData

enter image description here

相关问题