PathUpdate API

In Syncato 0.6 I added a Python API for constructing and modifying XML fragments using XPath specifiers. So far this has proven to be a really powerful way of working with XML fragments the way Syncato does.

The API is pretty simple.

class PathUpdate:            
    def addNode(self, path, content = None, markup = 0, createBase = 1):
            
    def updateNode(self, path, content = "", markup = 0):
                
    def removeNode(self, path):
            
    def insertNodeBefore(self, path, nodeName, content=None):
        
    def insertNodeAfter(self, path, nodeName, content=None):
            
    def getDocument(self):
        
    def serialize(self):


    

You can use it to create a new document. Here's an example to create a simple weblog post.

doc = PathUpdate()

doc.addNode("/item/title", "A sample title")
doc.addNode("/item/description", "Some body content with <markup>embedded</markup>", 1)


    

Printing this out then gives you a document that looks like this.

<item>
<title>A sample title</title>
<description>Some body content with <markup>embedded</markup></description>
</item>


    

Modifying is also easy

doc = PathUpdate(libxml2.parseDoc("<item><title>example</title></item>") 

doc.updateNode("/item/title", "Another example")


    

Of course you could also use a more complex query to select the node. If the query selects multiple nodes then all will be updated. Pretend this example has lots of title elements, but we only want to change those containing the word "example".

doc = PathUpdate(libxml2.parseDoc("<item><title>example</title></item>") 

doc.updateNode("/item/title[contains(., 'example')]", "Another example")


    

Right now the code is available as part of Syncato, but isn't tied to Syncato at all. It just depends on libxml2. Once it matures a little more I'll probably make the API available as a standalone download since it's quite powerful. It basically gives you an XML update language that uses Python syntax.

Posted by Kimbro Staken

Saturday Nov 15, 2003 at 8:35 AM
Recommended Sites