validation errors contain line and column number

Sun, 28 Jan 2024 13:26:47 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 28 Jan 2024 13:26:47 +0100
changeset 112
206e91a8dd18
parent 111
cb128bae1161
child 113
24f32dbd88cd

validation errors contain line and column number

src/main/java/de/unixwork/uwproj/Main.java file | annotate | diff | comparison | revisions
--- a/src/main/java/de/unixwork/uwproj/Main.java	Sun Jan 28 13:22:02 2024 +0100
+++ b/src/main/java/de/unixwork/uwproj/Main.java	Sun Jan 28 13:26:47 2024 +0100
@@ -2,11 +2,10 @@
 
 import org.apache.velocity.VelocityContext;
 import org.apache.velocity.app.VelocityEngine;
-import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
 
 import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.SchemaFactory;
 import java.io.*;
@@ -31,6 +30,9 @@
             final var schema = factory.newSchema(new StreamSource(xsdResource));
             final var validator = schema.newValidator();
 
+            // Validate the XML as stream (DOM validation cannot output line numbers in error message)
+            validator.validate(new StreamSource(new File(fileName)));
+
             // Load the DOM from the input file
             final var dom = DocumentBuilderFactory.
                     newDefaultNSInstance().
@@ -38,13 +40,13 @@
                     parse(fileName).
                     getDocumentElement();
 
-            // Validate the XML
-            validator.validate(new DOMSource(dom));
-
             // Parse the XML
             return new Project(dom);
-        } catch (SAXException saxerror) {
-            System.err.println(saxerror.getMessage());
+        } catch (SAXParseException saxerror) {
+            System.err.printf("Parse error in line %d, column %d: %s",
+                    saxerror.getLineNumber(),
+                    saxerror.getColumnNumber(),
+                    saxerror.getMessage());
             throw new RuntimeException("XML validation failed.");
         } catch (Exception e) {
             throw new RuntimeException(e);

mercurial