Package Products :: Package ZenUtils :: Module xmlutils
[hide private]
[frames] | no frames]

Source Code for Module Products.ZenUtils.xmlutils

 1  ########################################################################### 
 2  # 
 3  # This program is part of Zenoss Core, an open source monitoring platform. 
 4  # Copyright (C) 2007, Zenoss Inc. 
 5  # 
 6  # This program is free software; you can redistribute it and/or modify it 
 7  # under the terms of the GNU General Public License version 2 or (at your 
 8  # option) any later version as published by the Free Software Foundation. 
 9  # 
10  # For complete information please visit: http://www.zenoss.com/oss/ 
11  # 
12  ########################################################################### 
13   
14  from lxml import etree 
15   
16 -class XsdValidator(object):
17 """ 18 This validator uses lxml to validate XML files against schemas defined by 19 XSD files. 20 """ 21
22 - def __init__(self, xsd_path):
23 self.xsd_path = xsd_path 24 self.load_xsd(self.xsd_path)
25
26 - def load_xsd(self, xsd_path):
27 """ 28 Load the XSD schema at `xsd_path`. 29 """ 30 with open(xsd_path) as schema_file: 31 xml_schema_doc = etree.parse(schema_file) 32 self.xml_schema = etree.XMLSchema(xml_schema_doc) 33 return self.xml_schema
34
35 - def validate_path(self, path):
36 """ 37 Determine whether the file at `path` is valid using the configured xml schema. 38 """ 39 with open(path) as xml_file: 40 return self.validate_file(xml_file)
41
42 - def validate_file(self, f):
43 """ 44 Determine whether a file is valid using the configured xml schema. 45 """ 46 return self.xml_schema.validate(etree.parse(f))
47
48 - def check_path(self, path):
49 """ 50 This method will throw exceptions when trying to validate a path. 51 """ 52 with open(path) as xml_file: 53 return self.check_file(xml_file)
54
55 - def check_file(self, xml_file):
56 """ 57 This method will throw exceptions when trying to validate a file. 58 """ 59 return self.xml_schema.assertValid(etree.parse(xml_file))
60