简体   繁体   中英

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>

try this function.

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

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM