简体   繁体   中英

How to insert node into existing node in xml file inside baseX database from python client?

I'm trying to insert a xml node from string into an existing xml file in a BaseX XML-DB into an existing xml node.

This works from BaseX Editor, but it fails from BaseX Python client.

Other queries are working from python.

My XML in DB before:
mydata.xml

<a/>

Executed in BaseX Editor:

let $col := collection("mydb/mypath/mydata.xml")
let $inp := "<b><c>My Content</c></b>"
for $doc in $col  
return insert node fn:parse-xml($inp) into $doc//a  

Result XML:
mydata.xml

<a>
  <b>
    <c>My Content</c>
  </b>
</a>

This works fine.

But if I do the same from the Python Client, my XML in DB is untouched:

In Python:

session = BaseXClient.Session(DB_HOST, DB_PORT, DB_USER, DB_PASS)
session.execute("open mydb")
query = session.query(
""" 
  let $col := collection("mydb/mypath/mydata.xml")
  let $inp := "<b><c>My Content</c></b>"
  for $doc in $col
    return insert node fn:parse-xml($inp) into $doc//a
""")

Result: mydata.xml

<a/>

The DB Session in Python works, I can do other queries without problems.

So I don't know whats the problem here, no error occurs. But nodes are not inserted.

How do I insert my and node with my content from python in an existing mydata.xml with existing node inside this node?

Thanks!

Try this:

try:
    session = BaseXClient.Session(DB_HOST, DB_PORT, DB_USER, DB_PASS)
    query = 'let $col := collection("mydb/mypath/mydata.xml") ' \
            'let $inp := "<b><c>My Content</c></b>" ' \
            'for $doc in $col ' \
            'return insert node fn:parse-xml($inp) into $doc//a'
    queryObject = session.query(query)
    queryObject.execute()
    queryObject.close()

finally:
    if session:
        session.close()

Don't run this script while the BaseX database is opened, like opening on BaseX GUI while you're working on the Python script, for instance.

Make sure you always try the query first on the GUI (in a dummy database) and then deploy on the Python side.

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