Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * =====================================================
   *   _____                _     ____  _   _       _   _
   *  |_   _|_ __ _   _ ___| |_  / __ \| | | | ___ | | | |
   *    | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
   *    | | | |  | |_| \__ \ |_| | (_| |  _  |\__ \|  _  |
   *    |_| |_|   \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
   *                             \____/
  * 
  * =====================================================
  * 
  * Hochschule Hannover
  * (University of Applied Sciences and Arts, Hannover)
  * Faculty IV, Dept. of Computer Science
  * Ricklinger Stadtweg 118, 30459 Hannover, Germany
  * 
  * Email: trust@f4-i.fh-hannover.de
  * Website: http://trust.f4.hs-hannover.de/
  * 
  * This file is part of ifmapj, version 2.3.0, implemented by the Trust@HsH
  * research group at the Hochschule Hannover.
  * %%
  * Copyright (C) 2010 - 2015 Trust@HsH
  * %%
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * #L%
  */
 package util;
 
 
 
 import java.net.URI;
Modifed version of James Clark's XMLTest This tests an XML parser that has a SAX driver, by generating the canonical XML for one or more XML files. This is not written with performance in mind.

Modified by MHK to be callable from code and deliver the canonical XML as a string. Added an option to remove whitespace-only text nodes Added code to output all namespace nodes

Version:
Date: 1999/12/10 Taken from: http://www.cs.duke.edu/courses/fall08/cps116/docs/saxon/drivers/java/test/CanonicalXML.java and it seems to come from: http://www.jclark.com/xml/XMLTest.java
 
 public class CanonicalXML extends DefaultHandler implements LexicalHandler {
 
 	private StringWriter mOut;
 	private StringBuffer mBuf = new StringBuffer();
 	private boolean mStrip = false;
 	private boolean mIsWhite = true;
 
 	public String toCanonicalXml(XMLReader parserInputSource inputSourceboolean stripSpace) {
 
 		 = stripSpace;
 		 = new StringWriter();
 
 		parser.setContentHandler(this);
 		try {
 			parser.setProperty("http://xml.org/sax/properties/lexical-handler"this);
 		} catch (SAXNotSupportedException err) {	// this just means we won't see the comments
 		} catch (SAXNotRecognizedException err) {
 		}
		parser.setErrorHandler(this);
		try {
			parser.parse(inputSource);
			return .toString();
catch (SAXParseException e) {
			..println("XML parsing error on line " + e.getLineNumber() + " while creating Canonical XML");
			//e.printStackTrace();
			..println("Parser: " + parser.getClass());
			try {
				..println("Supports XML 1.1: " + parser.getFeature("http://xml.org/sax/features/xml-1.1"));
catch (Exception e2) { }
catch (SAXException e) {
			..println("XML parsing error while creating Canonical XML");
catch (IOException e) {
			..println("XML parsing error while creating Canonical XML");
		}
		return null;
	}


Create canonical XML silently, throwing exceptions rather than displaying messages

Parameters:
parser
inputSource
stripSpace
Returns:
Throws:
java.lang.Exception
	public String toCanonicalXml2(XMLReader parserInputSource inputSourceboolean stripSpacethrows Exception {
		 = stripSpace;
		 = new StringWriter();
		parser.setContentHandler(this);
		parser.setErrorHandler(this);
		parser.parse(inputSource);
		return .toString();
	}

Create canonical XML silently, throwing exceptions rather than displaying messages. This version of the method uses the Saxon identityTransformer rather than parsing directly, because for some reason we seem to be able to get XML 1.1 to work this way.
	public String toCanonicalXml3(TransformerFactory factoryXMLReader resultParserString inxmlboolean stripSpace)
			throws Exception {
		 = stripSpace;
		 = new StringWriter();
		Transformer t = factory.newTransformer();
		SAXSource ss = new SAXSource(resultParsernew InputSource(new StringReader(inxml)));
		ss.setSystemId("http://localhost/string-input");
		t.transform(ssnew SAXResult(this));
		return .toString();
	}

Receive notification of the start of a Namespace mapping.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each Namespace prefix scope (such as storing the prefix mapping).

Parameters:
prefix The Namespace prefix being declared.
uri The Namespace URI mapped to the prefix.
Throws:
org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
See also:
org.xml.sax.ContentHandler.startPrefixMapping(java.lang.String,java.lang.String)
	public void startPrefixMapping(String prefixString urithrows SAXException {
		.addAttribute(""prefixprefix.equals("") ? "xmlns" : "xmlns:" + prefix"CDATA"uri);
		if (!"".equals(uri)) {
			try {
				URI u = new URI(uri);
				if (!u.isAbsolute()) {
					..println("*** (Canonical XML:) namespace URI " + u + " is not absolute");
				}
catch (URISyntaxException err) {
				..println("*** (Canonical XML:) namespace " + uri + " is not a valid URI");
			}
		}
	}

Receive notification of the start of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each element (such as allocating a new tree node or writing output to a file).

Parameters:
uri The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
localName The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName The qualified name (with prefix), or the empty string if qualified names are not available.
atts The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
Throws:
org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
See also:
org.xml.sax.ContentHandler.startElement(java.lang.String,java.lang.String,java.lang.String,org.xml.sax.Attributes)
	public void startElement(String uriString localNameString qNameAttributes attsthrows SAXException {
		write("<");
		write(qName);
		// output the namespaces
		// output the attributes
		write(">");
	}
	private void outputAttributes(Attributes atts) {
		int len = atts.getLength();
		if (len > 0) {
			int[] v = new int[len];
			for (int i = 0; i < leni++) {
				v[i] = i;
			}
			/* Do an insertion sort. */
			for (int i = 1; i < leni++) {
				int n = v[i];
				String s = atts.getQName(n);
				int j;
				for (j = i - 1; j >= 0; j--) {
					if (s.compareTo(atts.getQName(v[j])) >= 0) {
						break;
					}
					v[j + 1] = v[j];
				}
				v[j + 1] = n;
			}
			for (int i = 0; i < leni++) {
				write(" ");
				int n = v[i];
				write(atts.getQName(n));
				write("=\"");
				String value = atts.getValue(n);
				int valueLen = value.length();
				for (int j = 0; j < valueLenj++) {
					appendChar(value.charAt(j));
				}
				write("\"");
			}
		}
	}
	public void ignorableWhitespace(char[] cbufint startint len) {
		characters(cbufstartlen);
	}
	public void characters(char[] cbufint startint len) {
		while (len-- > 0) {
			appendChar(cbuf[start++]);
		}
	}
	private void appendChar(char c) {
		if ( && ) {
			if (!Character.isWhitespace(c)) {
				 = false;
			}
		}
		switch (c) {
			case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 11: case 12:
			case 14: case 15:
				break;
			case '&':
				.append("&amp;");
				break;
			case '<':
				.append("&lt;");
				break;
			case '>':
				.append("&gt;");
				break;
			case '"':
				.append("&quot;");
				break;
			case '\t':
				.append("&#9;");
				break;
			case '\n':
				.append("&#10;");
				break;
			case '\r':
				.append("&#13;");
				break;
			case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135:
			case 136: case 137: case 138: case 139: case 140: case 141: case 142: case 143:
			case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151:
			case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159:
			case 160:
				break;
			default:
				break;
		}
	}
	private String charRef(char c) {
		return "&#" + (intc + ";";
	}

Receive notification of the end of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of each element (such as finalising a tree node or writing output to a file).

Parameters:
uri The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
localName The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName The qualified name (with prefix), or the empty string if qualified names are not available.
Throws:
org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
See also:
org.xml.sax.ContentHandler.endElement(java.lang.String,java.lang.String,java.lang.String)
	public void endElement(String uriString localNameString qNamethrows SAXException {
		write("</");
		write(qName);
		write(">");
	}
	public void processingInstruction(String targetString datathrows SAXException {
		write("<?");
		write(target);
		write(" ");
		write(data);
		write("?>");
	}
	public void startDocument() {
	}
	public void endDocument() throws SAXException {
		try {
catch (IOException e) {
			throw new SAXException(e);
		}
	}
	public void startDTD(String nameString publicIdString systemIdthrows SAXException {
		//
	}
	public void endDTD() throws SAXException {
		//
	}
	public void startEntity(String namethrows SAXException {
		//
	}
	public void endEntity(String namethrows SAXException {
		//
	}
	public void startCDATA() throws SAXException {
		//
	}
	public void endCDATA() throws SAXException {
		//
	}
	public void comment(char []chint startint lengththrows SAXException {
		write("<!--");
		write(new String(chstartlength));
		write("-->");
	}
	private void flushChars() {
		if (.length() > 0 && !( && )) {
		}
		 = true;
	}
	private void write(String s) {
		int len = s.length();
		for (int i = 0; i < leni++) {
			char c = s.charAt(i);
			if (c < 0x80) {
else {
				switch (c & 0xF800) {
					case 0:
						.write(c >> 6 & 0x1F | 0xC0);
						.write(c & 0x3F | 0x80);
						break;
					case 0xD800:
						char c2;
						if (i + 1 < len
								&& (c & 0xFC00) == 0xD800
								&& ((s.charAt(i + 1)) & 0xFC00) == 0xDC00) {
							c2 = s.charAt(i + 1);
							++i;
							int n = (c & 0x3FF) << 10 | c2 & 0x3FF;
							n += 0x10000;
							.write(n >> 18 & 0x7 | 0xF0);
							.write(n >> 12 & 0x3F | 0x80);
							.write(n >> 6 & 0x3F | 0x80);
							.write(n & 0x3F | 0x80);
							break;
						}
						/* this is an error situation really */
						/* fall through */
					default:
						.write(c >> 12 & 0xF | 0xE0);
						.write(c >> 6 & 0x3F | 0x80);
						.write(c & 0x3F | 0x80);
						break;
				}
			}
		}
	}
New to GrepCode? Check out our FAQ X