0
votes

Following is the structure of my XML File -

<Doc>
  <P n="1"/>
  <P>blah blah blah. <B>Pg-1</B></P>
  <P n="2"/>
  <P>blah blah blah. <B>Pg-2</B></P>
</Doc>

I have to change it to -

<Doc>
  <P n="1">blah blah blah. <B>Pg-1</B></P>
  <P n="2">blah blah blah. <B>Pg-2</B></P>
</Doc>

How to do this ?

2

2 Answers

1
votes

If your query processor supports XQuery Update, this is another solution:

copy $doc :=
  <Doc>
    <P n="1"/>
    <P>blah blah blah. <B>Pg-1</B></P>
    <P n="2"/>
    <P>blah blah blah. <B>Pg-2</B></P>
  </Doc>
modify (
  for $p1 in $doc/P[@n]
  let $p2 := $p1/following-sibling::P[1]
  return (
    insert node $p2/node() into $p1,
    delete node $p2
  )
)
return $doc
1
votes

This is a bit tricky, here is what I came up with. I'm not sure if there is a nicer way though.

for $pn in Doc/P[@n] 
  let $nextPn := $pn/following-sibling::P[@n]
  let $pGroup := ($pn union $pn/following-sibling::P) except ($nextPn union $nextPn/following-sibling::P)
return <P>{$pn/attribute(), $pGroup/node()}</P>