This section contains some easy-to-use functions, to be used as is without too much hassle within fabfiles:
Prints the matching entries (whereas query() only returns elements)
# fabfile.py
from fabric.contrib import xfiles
def mycommand(rpath):
"""
Lists the elements of remote document.
"""
xfiles.pprint(rpath, 'items/item[attr=value]')
And to run fabfile:
fab mycommand:document.xml
Makes query to remote XML file and returns the matching entries back
XQuery -like selection for the elements/values in the XML document. Selection format:
path/to/elements # <-- matches to elements -element
/root/path/to/elements # <-- absolute selection example
path/to=value # <-- matches with 'to' element when having text 'value' in it
path/to=val* # <-- matches with 'to' element when having text starting with 'val'
path/to/elements[id] # <-- matches to all elements having 'id' attribute
path/to/elements[@id] # <-- same as above
path/to/elements[i?] # <-- matches to all attributes with 'i'+something
path/to/elements[i*] # <-- matches to all attributes with 'i'
path/to/elements[id=value] # <-- matches to all elements having 'id' attribute with value 'value'
path/to/elements[@id=value] # <-- same as above
path/to/elements[id=val*] # <-- matches to all elements having 'val'+something
path/to/elements[i?=val*] # <-- combination from above
path/to[i?=val*]=val* # <-- combination from all of the above
Note
Wildcard are not supported for paths - at least not yet. So, for example, following is not supported:
path/to/elem*
Example usage:
# fabfile.py
from fabric.contrib import xfiles
def mycommand():
for elem in xfiles.query('path/to/remotedoc.xml', 'items/item'):
print elem.text, elem.attrib
And to run fabfile:
fab mycommand
Validates the given XML document, based on provided schema (if at all):
If none of these schema files are provided, the basic XML document parsing is done to ensure the validity of the document.
If the validation fails, the exception is thrown, hopefully with descriptive message why the validation did not pass. If fail_on_error is set False, the function returns False on failure. Otherwise True.
Example
from fabric.contrib import xfiles
def check():
#Checks the setup config validity
dtd = 'server-config.dtd'
xsd = 'config.xsd'
try:
xfiles.validate('/etc/appx/server.xml', dtd=dtd)
xfiles.validate('/etc/appx/application.xml', xmlschema=xsd)
except Exception e:
print 'Validation FAILED: %s' % e
Note
Schema validations requires lxml module to be installed on local environment.
For more advanced usage, this section lists the contents of the API:
XMLReader for remote files, using Fabric
from fabric.contrib.xfiles import reader
rxr = reader.RXMLReader()
rxr.open('/tmp/document.xml')
rxr.query('/root/path/items')
# do something with the result set
rxr.close()
Reads the XML document from remote location and stores the parsed document into self.etree
Makes a query to retrived XML file.