s_u_f
s_u_f

Reputation: 200

How to add an attribute to an existing node using Xquery

I have an xml as below.

<test>
<a att1="1">
</test>

How to add an new attribute to the existing node ? Expected output is as follows.

<test>
<a att1="1" att2="2">
</test>

Upvotes: 0

Views: 3831

Answers (3)

John
John

Reputation: 2852

Using XQuery Update and BaseX, following will be the solution -

for $x in doc('Document2')//a
return 
insert node attribute att2{'2'} into $x

I hope you already have the answer, still...

Upvotes: 1

s_u_f
s_u_f

Reputation: 200

Solved the issue with the below Xquery in MarkLogic.

(: create a document :)
xdmp:document-insert("/example.xml", <a/>);

(: insert an attribute as child of a :)    
xdmp:node-insert-child(doc("/example.xml")/a,
attribute b { "bbb" });

(: look at the new document :)
fn:doc("/example.xml")

**Output**

<?xml version="1.0" encoding="UTF-8"?>
<a b="bbb"/>

Source : xdmp:node-insert-child

Upvotes: 0

Kevin Andrid
Kevin Andrid

Reputation: 1961

try this function.

  functx:add-attributes(
  $in-xml/a,
  (xdmp:node-insert-after('att1','att2')) or (xdmp:node-insert-before('att1','att2')),(1,2)).

Upvotes: 1

Related Questions