Search code examples
xquerybasexxquery-update

XQuery - to insert splitted nodes data into another node


<?xml version="1.0" encoding="UTF-8"?>
<Data>
  <A><DelInfo>123-20150308-345</DelInfo><OrderNo>11</OrderNo></A>
  <A><DelInfo>1204-20150308-355</DelInfo><OrderNo>15</OrderNo></A>
  <A><DelInfo>153-20150408-343</DelInfo><OrderNo>10</OrderNo></A>
  <A><DelInfo>44345-20150308-341</DelInfo><OrderNo>21</OrderNo></A>
  <A><DelInfo>153-20150204-245</DelInfo><OrderNo>1</OrderNo></A>
  <A><DelInfo>423-20150311-445</DelInfo><OrderNo>13</OrderNo></A>
  ..........
</Data>

I receive following XML. The DelInfo node contains a combination of EmpId, Delivery Date and Receipt No. The OrderNo node contains the order number wrt the Delivery Information.

The XML is stored in BaseX and I need following report to be generated from the above XML.

<A><DelInfo>123-20150308-345</DelInfo><OrderNo>11</OrderNo><Report>20150308 - 11</Report></A>
.....

In other word, I want to insert an additional node Report with Date and Order No. Any idea?


Solution

  • Replace yourdoc with your document name.

    for $x in doc('yourdoc')//A
      let $d := substring-before(substring-after($x/DelInfo, "-"), "-")
      let $o := $x/OrderNo/text()
      let $i := <C>{concat($d, " - ", $o)}</C>
    return 
        insert node $i after $x/OrderNo
    

    The inner substring-after() will return the string after the first -. Then, the substring-before() will return the string before the -. This way you will get the Date portion.