Wednesday, 17 February 2021

Update XML with an SQL query

Let's say we have the following XML file:

from lxml import etree
root = etree.fromstring("""
    <a>
        <b>
            <c>Hello</c>
            <d>1234</d>
        </b>
        <b>
            <c>Bonjour</c>
            <d>5678</d>
        </b>        
    </a>
    """)

How could it be possible to update the XML with a SQL-like query language?

Example (pseudo-code):

etree.query("""UPDATE a.b SET c.text = 'foo' WHERE d.text = '5678'""")

or even more complex chained-queries, such as:

UPDATE a.b SET c.text = (SELECT ... FROM ... WHERE ...) WHERE d.text = '5678'

The goal is to be able to modify complex XML documents with just one or two lines of code, with a SQL-like syntax. Sidenote: As a comparison, doing this manually with lxml, find, etc. works, but is much longer.



from Update XML with an SQL query

No comments:

Post a Comment