Changing node name via Xquery

592 Views Asked by At

I am trying to create an xquery which will change the name of the node from 'CNode3' to 'ChangedNode3' whenever the child element ('CCNode1') of 'CNode3' is 'CCValue1'.

<PNode>
  <CNode1>Node1</CNode1>
  <CNode2>Node2</CNode2>
  <CNode3>
     <CCNode1>CCValue1</CCNode1>
     <CCNode2>CCValue2</CCNode2>
  </CNode3>
  <CNode3>
     <CCNode1>CCValue3</CCNode1>
     <CCNode2>CCValue4</CCNode2>
  </CNode3></PNode>

Didn't get much help online for this particular scenario. I checked below link but it changes the name of all 'CNode3' to 'ChangedNode3'. PFB the link: http://www.xqueryfunctions.com/xq/functx_change-element-names-deep.html

1

There are 1 best solutions below

0
Mads Hansen On

The functx:change-element-names-deep() function only evaluates the element names. You need a bit more customization.

You can use typeswitch in a local function:

declare function local:transform($nodes as node()*) as item()* {
    for $node in $nodes
    return 
        typeswitch($node)
            case text() return $node
            case comment() return $node
            case attribute() return $node
            case processing-instruction() return $node
            case element(CNode3) 
              return 
                if ($node[CCNode1 eq "CCValue1"]) then 
                  element ChangedNode3 {( $node/@*, local:transform($node/node()) )} 
                else 
                  element {name($node)} {($node/@*, local:transform($node/node()))}
            case element() 
              return element {name($node)} {($node/@*, local:transform($node/node()))}
            default return local:transform($node/node())
};

A full description of the typeswitch transformation pattern.