Debian Codegraph @

net/sf/saxon/event/DocumentValidator.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.event;
9
10 import net.sf.saxon.expr.parser.Location;
11 import net.sf.saxon.om.NodeName;
12 import net.sf.saxon.trans.Err;
13 import net.sf.saxon.trans.XPathException;
14 import net.sf.saxon.type.SchemaType;
15 import net.sf.saxon.value.Whitespace;
16
17 /**
18 * DocumentValidator checks that a document is well-formed: specifically, that it contains a single element
19 * node child and no text node children.
20 */
21
22 public class DocumentValidator extends ProxyReceiver {
23 private boolean foundElement = false;
24 private int level = 0;
25 private String errorCode;
26
27 public DocumentValidator(Receiver next, String errorCode) {
28 super(next);
29 this.errorCode = errorCode;
30 }
31
32 public void setPipelineConfiguration(/*@NotNull*/ PipelineConfiguration config) {
33 super.setPipelineConfiguration(config);
34 }
35
36 /**
37 * Start of an element
38 */
39
40 public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException {
41 if (foundElement && level == 0) {
42 throw new XPathException("A valid document must have only one child element", errorCode);
43 }
44 foundElement = true;
45 level++;
46 nextReceiver.startElement(nameCode, typeCode, location, properties);
47 }
48
49 /**
50 * Character data
51 */
52
53 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
54 if (level == 0) {
55 if (Whitespace.isWhite(chars)) {
56 return; // ignore whitespace outside the outermost element
57 }
58 throw new XPathException("A valid document must contain no text outside the outermost element (found \"" + Err.truncate30(chars) + "\")", errorCode);
59 }
60 nextReceiver.characters(chars, locationId, properties);
61 }
62
63 /**
64 * End of element
65 */
66
67 public void endElement() throws XPathException {
68 level--;
69 nextReceiver.endElement();
70 }
71
72 /**
73 * Notify the end of a document node
74 */
75
76 public void endDocument() throws XPathException {
77 if (level == 0) {
78 if (!foundElement) {
79 throw new XPathException("A valid document must have a child element", errorCode);
80 }
81 foundElement = false;
82 nextReceiver.endDocument();
83 level = -1;
84 }
85 }
86 }
87
88 // Copyright (c) 2004-2007 Saxonica Limited
89