0

I want to delete some nodes from menu xml that is being stored in a typed xml column in database.
Snippet from menu xml -

<menu xmlns="http://xxx" ..>
<menuItem name="Menu1">
    <menuItem name="SubMenu1">
        <role>role1</role>
        <url target="webPage1.aspx" />
    </menuItem> 
</menuItem> 

I am trying to delete <role> under menuItem = "SubMenu1" using following XML DML -

UPDATE [dbo].[MenuTest]
SET xmlMenu.modify('
    declare namespace ns="http://xxx";
    delete(/ns:menu/ns:menuItem[@name="Menu1"]/ns:menuItem[@name="SubMenu1"]/ns:role[1])
')

But getting this error:

Msg 6965, Level 16, State 1, Line 1
XML Validation: Invalid content. Expected element(s):http://xxx:role where element 'http://xxx:url' was specified.

Can please guide what I am missing here.

Thank you!

1 Answer 1

1

It looks like your XML column is hooked up to a XML-schema that requires a <role> node before the <url> node.

What you have posted here works just fine.

declare @T table 
(
  xmlMenu xml
)

insert into @T values
('<menu xmlns="http://xxx">
     <menuItem name="Menu1">
       <menuItem name="SubMenu1">
         <role>role1</role>
         <url target="webPage1.aspx" />
       </menuItem> 
    </menuItem>
  </menu>')


UPDATE @T
SET xmlMenu.modify('
    declare namespace ns="http://xxx";
    delete(/ns:menu/ns:menuItem[@name="Menu1"]/ns:menuItem[@name="SubMenu1"]/ns:role[1])
')

Result

<menu xmlns="http://xxx">
  <menuItem name="Menu1">
    <menuItem name="SubMenu1">
      <url target="webPage1.aspx" />
    </menuItem>
  </menuItem>
</menu>
Sign up to request clarification or add additional context in comments.

5 Comments

Good to know :-) Can also please guide how can I delete node with text 'role1', so if I have multiple <role/> nodes, I want to delete only those having particular text values.
@iniki - just replace ns:role[1] with ns:role[. = "role1"] and it will delete all <role> nodes with value role1.
Thanks for your reply, but I am getting this error - Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element(ns{xxx}:role,xs:anyType)'.
@inki - Works for me, try it here: data.stackexchange.com/stackoverflow/qt/121279
it's again seems some XML schema issue :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.