plcopen/plcopen.py
changeset 1330 96b242e4c59d
parent 1322 0a9227f743b3
child 1331 38c5de794e62
--- a/plcopen/plcopen.py	Wed Sep 25 11:50:40 2013 +0200
+++ b/plcopen/plcopen.py	Fri Sep 27 16:22:40 2013 +0200
@@ -156,35 +156,44 @@
   </body>
 </pou>""" % locals()
 
-def LoadProject(filepath):
-    project_file = open(filepath)
-    project_xml = project_file.read().replace(
+def LoadProjectXML(project_xml):
+    project_xml = project_xml.replace(
         "http://www.plcopen.org/xml/tc6.xsd", 
         "http://www.plcopen.org/xml/tc6_0201")
     for cre, repl in [
         (re.compile("(?<!<xhtml:p>)(?:<!\[CDATA\[)"), "<xhtml:p><![CDATA["),
         (re.compile("(?:]]>)(?!</xhtml:p>)"), "]]></xhtml:p>")]:
         project_xml = cre.sub(repl, project_xml)
+    
+    try:
+        tree, error = PLCOpenParser.LoadXMLString(project_xml)
+        if error is not None:
+            # TODO Validate file according to PLCOpen v1 and modify it for
+            # compatibility with PLCOpen v2
+            return tree, error
+        return tree, None
+    except Exception, e:
+        return None, e.message
+
+def LoadProject(filepath):
+    project_file = open(filepath)
+    project_xml = project_file.read()
     project_file.close()
-    
-    return etree.fromstring(project_xml, PLCOpenParser)
+    return LoadProjectXML(project_xml)
 
 project_pou_xpath = PLCOpen_XPath("/ppx:project/ppx:types/ppx:pous/ppx:pou")
 def LoadPou(xml_string):
-    root = etree.fromstring(
-        LOAD_POU_PROJECT_TEMPLATE % xml_string, 
-        PLCOpenParser)
-    return project_pou_xpath(root)[0]
+    root, error = LoadProjectXML(LOAD_POU_PROJECT_TEMPLATE % xml_string)
+    return project_pou_xpath(root)[0], error
 
 project_pou_instances_xpath = {
     body_type: PLCOpen_XPath(
         "/ppx:project/ppx:types/ppx:pous/ppx:pou[@name='paste_pou']/ppx:body/ppx:%s/*" % body_type)
     for body_type in ["FBD", "LD", "SFC"]}
 def LoadPouInstances(xml_string, body_type):
-    root = etree.fromstring(
-        LOAD_POU_INSTANCES_PROJECT_TEMPLATE(body_type) % xml_string, 
-        PLCOpenParser)
-    return project_pou_instances_xpath[body_type](root)
+    root, error = LoadProjectXML(
+        LOAD_POU_INSTANCES_PROJECT_TEMPLATE(body_type) % xml_string)
+    return project_pou_instances_xpath[body_type](root), error
 
 def SaveProject(project, filepath):
     project_file = open(filepath, 'w')