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

# Source Code for Module Products.ZenUtils.xmlutils

     1  ##############################################################################
     2  #
     3  # Copyright (C) Zenoss, Inc. 2007, all rights reserved.
     4  #
     5  # This content is made available according to terms specified in
     6  # License.zenoss under the directory where your Zenoss product is installed.
     7  #
     8  ##############################################################################
     9
    10
    11  from lxml import etree
    12
    13 -class XsdValidator(object):
    14      """
    15      This validator uses lxml to validate XML files against schemas defined by
    16      XSD files.
    17      """
    18
    19 -    def __init__(self, xsd_path):
    20          self.xsd_path = xsd_path
    21          self.load_xsd(self.xsd_path)
    22
    23 -    def load_xsd(self, xsd_path):
    24          """
    25          Load the XSD schema at `xsd_path`.
    26          """
    27          with open(xsd_path) as schema_file:
    28              xml_schema_doc = etree.parse(schema_file)
    29              self.xml_schema = etree.XMLSchema(xml_schema_doc)
    30              return self.xml_schema
    31
    32 -    def validate_path(self, path):
    33          """
    34          Determine whether the file at `path` is valid using the configured xml schema.
    35          """
    36          with open(path) as xml_file:
    37              return self.validate_file(xml_file)
    38
    39 -    def validate_file(self, f):
    40          """
    41          Determine whether a file is valid using the configured xml schema.
    42          """
    43          return self.xml_schema.validate(etree.parse(f))
    44
    45 -    def check_path(self, path):
    46          """
    47          This method will throw exceptions when trying to validate a path.
    48          """
    49          with open(path) as xml_file:
    50              return self.check_file(xml_file)
    51
    52 -    def check_file(self, xml_file):
    53          """
    54          This method will throw exceptions when trying to validate a file.
    55          """
    56          return self.xml_schema.assertValid(etree.parse(xml_file))
    57