| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 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 |
|
| 19 |
|
| 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( PipelineConfiguration config) { |
| 33 |
super.setPipelineConfiguration(config); |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
|
| 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 |
|
| 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; |
| 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 |
|
| 65 |
|
| 66 |
|
| 67 |
public void endElement() throws XPathException { |
| 68 |
level--; |
| 69 |
nextReceiver.endElement(); |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
|
| 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 |
|
| 89 |
|