How to modify XML node that contains a specific child node value?

隐身守侯 提交于 2020-01-05 07:33:10

问题


I have a table with an XML column. How can I add another node inside a node that contains a child node with a specific value? For example I'd like to copy foo/bar/e/f node from barId 6699 to barId 66989. I only find examples where you select node based on an attribute value. I need to filter by child node value instead.

<foo>
    <bar>
        <barId>66988</barId>
        <name>baz 3</name>
    </bar>
    <bar>
        <barId>66989</barId>
        <name>b </name>
        <e>
            <g>
                <h>
                    <l>-</l>
                    <m>k</m>
                </h>
                <h>
                    <l>p  v</l>
                    <m>k</m>
                </h>
            </g>
        </e>
    </bar>
    <bar>
        <barId>6699</barId>
        <name>n 4 c</name>
        <e>
            <f>
                <h>
                    <i>k</i>
                    <j>9.3</j>
                </h>
            </f>
        </e>
    </bar>
</foo>

回答1:


Try this:

DECLARE @value XML = '<foo><bar><barId>66988</barId><name>baz 3</name></bar><bar><barId>66989</barId><name>b </name><e><g><h><l>-</l><m>k</m></h><h><l>p  v</l><m>k</m></h></g></e></bar><bar><barId>6699</barId><name>n 4 c</name><e><f><h><i>k</i><j>9.3</j></h></f></e></bar></foo>';

DECLARE @SourceID INT = 6699;
DECLARE @DestinationID INT = 66989;

DECLARE @temp XML;

SELECT @temp = T.c.query('.')
FROM @value.nodes('/foo/bar[barId = sql:variable("@SourceID")]/e/f') T(c);

SELECT @temp;

SET @value.modify('insert sql:variable("@temp") as last into (/foo/bar[barId =sql:variable("@DestinationID")]/e)[1]')

SELECT @value;

It will give you this:

<foo>
  <bar>
    <barId>66988</barId>
    <name>baz 3</name>
  </bar>
  <bar>
    <barId>66989</barId>
    <name>b </name>
    <e>
      <g>
        <h>
          <l>-</l>
          <m>k</m>
        </h>
        <h>
          <l>p  v</l>
          <m>k</m>
        </h>
      </g>
      <f>
        <h>
          <i>k</i>
          <j>9.3</j>
        </h>
      </f>
    </e>
  </bar>
  <bar>
    <barId>6699</barId>
    <name>n 4 c</name>
    <e>
      <f>
        <h>
          <i>k</i>
          <j>9.3</j>
        </h>
      </f>
    </e>
  </bar>
</foo>


来源:https://stackoverflow.com/questions/43998729/how-to-modify-xml-node-that-contains-a-specific-child-node-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!