Java/XML/Schema

Материал из Java эксперт
Версия от 07:11, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create XML validator from XML schema

    
 
 
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
public class Main {
  public static void main(String[] argv) throws Exception {
    String schemaLang = "http://www.w3.org/2001/XMLSchema";
    SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
    Schema schema = factory.newSchema(new StreamSource("sample.xsd"));
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource("sample.xml"));
  }
}





Encoder and Decoder for XML element and attribute names

  
/*
 * JBoss DNA (http://www.jboss.org/dna)
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * See the AUTHORS.txt file in the distribution for a full listing of 
 * individual contributors. 
 *
 * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
 * is licensed to you under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * JBoss DNA is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.BitSet;
/**
 * An {@link TextEncoder encoder} and {@link TextDecoder decoder} for XML element and attribute names.
 * <p>
 * Any UTF-16 unicode character that is not a valid XML name character according to the  is escaped as <code>_xHHHH_</code>, where <code>HHHH</code> stands for the four-digit
 * hexadecimal UTF-16 unicode value for the character in the most significant bit first order. For example, the name "Customer_ID"
 * is encoded as "Customer_x0020_ID".
 * </p>
 * <p>
 * Decoding transforms every <code>_xHHHH_</code> encoding sequences back into the UTF-16 character. Note that
 * {@link #decode(String) decoding} can be safely done on any XML name, even if the name does not contain any encoded sequences.
 * </p>
 * 
 * @author Randall Hauch
 */
public class XmlNameEncoder  {
    private static final BitSet XML_NAME_ALLOWED_CHARACTERS = new BitSet(2 ^ 16);
    static {
        // Initialize the unescaped bitset ...
        // XML Names may contain: Letter | Digit | "." | "-" | "_" | ":" | CombiningChar | Extender
        XML_NAME_ALLOWED_CHARACTERS.set(".");
        XML_NAME_ALLOWED_CHARACTERS.set("-");
        XML_NAME_ALLOWED_CHARACTERS.set("_");
        XML_NAME_ALLOWED_CHARACTERS.set(":");
        // XML Base Character Set
        XML_NAME_ALLOWED_CHARACTERS.set("\u0041", "\u005A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0061", "\u007A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u00C0", "\u00D6" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u00D8", "\u00F6" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u00F8", "\u00FF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0100", "\u0131" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0134", "\u013E" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0141", "\u0148" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u014A", "\u017E" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0180", "\u01C3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u01CD", "\u01F0" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u01F4", "\u01F5" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u01FA", "\u0217" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0250", "\u02A8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u02BB", "\u02C1" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0386");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0388", "\u038A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u038C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u038E", "\u03A1" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u03A3", "\u03CE" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u03D0", "\u03D6" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u03DA");
        XML_NAME_ALLOWED_CHARACTERS.set("\u03DC");
        XML_NAME_ALLOWED_CHARACTERS.set("\u03DE");
        XML_NAME_ALLOWED_CHARACTERS.set("\u03E0");
        XML_NAME_ALLOWED_CHARACTERS.set("\u03E2", "\u03F3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0401", "\u040C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u040E", "\u044F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0451", "\u045C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u045E", "\u0481" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0490", "\u04C4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u04C7", "\u04C8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u04CB", "\u04CC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u04D0", "\u04EB" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u04EE", "\u04F5" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u04F8", "\u04F9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0531", "\u0556" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0559");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0561", "\u0586" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u05D0", "\u05EA" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u05F0", "\u05F2" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0621", "\u063A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0641", "\u064A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0671", "\u06B7" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06BA", "\u06BE" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06C0", "\u06CE" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06D0", "\u06D3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06D5");
        XML_NAME_ALLOWED_CHARACTERS.set("\u06E5", "\u06E6" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0905", "\u0939" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u093D");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0958", "\u0961" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0985", "\u098C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u098F", "\u0990" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0993", "\u09A8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09AA", "\u09B0" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09B2");
        XML_NAME_ALLOWED_CHARACTERS.set("\u09B6", "\u09B9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09DC", "\u09DD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09DF", "\u09E1" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09F0", "\u09F1" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A05", "\u0A0A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A0F", "\u0A10" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A13", "\u0A28" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A2A", "\u0A30" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A32", "\u0A33" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A35", "\u0A36" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A38", "\u0A39" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A59", "\u0A5C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A5E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A72", "\u0A74" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A85", "\u0A8B" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A8D");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A8F", "\u0A91" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A93", "\u0AA8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0AAA", "\u0AB0" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0AB2", "\u0AB3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0AB5", "\u0AB9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0ABD");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0AE0");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B05", "\u0B0C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B0F", "\u0B10" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B13", "\u0B28" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B2A", "\u0B30" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B32", "\u0B33" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B36", "\u0B39" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B3D");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B5C", "\u0B5D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B5F", "\u0B61" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B85", "\u0B8A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B8E", "\u0B90" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B92", "\u0B95" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B99", "\u0B9A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B9C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B9E", "\u0B9F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BA3", "\u0BA4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BA8", "\u0BAA" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BAE", "\u0BB5" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BB7", "\u0BB9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C05", "\u0C0C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C0E", "\u0C10" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C12", "\u0C28" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C2A", "\u0C33" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C35", "\u0C39" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C60", "\u0C61" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C85", "\u0C8C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C8E", "\u0C90" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C92", "\u0CA8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CAA", "\u0CB3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CB5", "\u0CB9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CDE");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CE0", "\u0CE1" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D05", "\u0D0C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D0E", "\u0D10" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D12", "\u0D28" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D2A", "\u0D39" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D60", "\u0D61" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E01", "\u0E2E" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E30");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E32", "\u0E33" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E40", "\u0E45" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E81", "\u0E82" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E84");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E87", "\u0E88" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E8A");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E8D");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E94", "\u0E97" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E99", "\u0E9F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EA1", "\u0EA3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EA5");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EA7");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EAA", "\u0EAB" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EAD", "\u0EAE" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EB0");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EB2", "\u0EB3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EBD");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EC0", "\u0EC4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F40", "\u0F47" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F49", "\u0F69" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u10A0", "\u10C5" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u10D0", "\u10F6" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1100");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1102", "\u1103" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1105", "\u1107" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1109");
        XML_NAME_ALLOWED_CHARACTERS.set("\u110B", "\u110C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u110E", "\u1112" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u113C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u113E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1140");
        XML_NAME_ALLOWED_CHARACTERS.set("\u114C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u114E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1150");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1154", "\u1155" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1159");
        XML_NAME_ALLOWED_CHARACTERS.set("\u115F", "\u1161" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1163");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1165");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1167");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1169");
        XML_NAME_ALLOWED_CHARACTERS.set("\u116D", "\u116E" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1172", "\u1173" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1175");
        XML_NAME_ALLOWED_CHARACTERS.set("\u119E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u11A8");
        XML_NAME_ALLOWED_CHARACTERS.set("\u11AB");
        XML_NAME_ALLOWED_CHARACTERS.set("\u11AE", "\u11AF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u11B7", "\u11B8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u11BA");
        XML_NAME_ALLOWED_CHARACTERS.set("\u11BC", "\u11C2" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u11EB");
        XML_NAME_ALLOWED_CHARACTERS.set("\u11F0");
        XML_NAME_ALLOWED_CHARACTERS.set("\u11F9");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1E00", "\u1E9B" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1EA0", "\u1EF9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F00", "\u1F15" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F18", "\u1F1D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F20", "\u1F45" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F48", "\u1F4D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F50", "\u1F57" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F59");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F5B");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F5D");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F5F", "\u1F7D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1F80", "\u1FB4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FB6", "\u1FBC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FBE");
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FC2", "\u1FC4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FC6", "\u1FCC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FD0", "\u1FD3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FD6", "\u1FDB" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FE0", "\u1FEC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FF2", "\u1FF4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u1FF6", "\u1FFC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u2126");
        XML_NAME_ALLOWED_CHARACTERS.set("\u212A", "\u212B" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u212E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u2180", "\u2182" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u3041", "\u3094" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u30A1", "\u30FA" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u3105", "\u312C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\uAC00", "\uD7A3" + 1);
        // XML Ideograph Character Set
        XML_NAME_ALLOWED_CHARACTERS.set("\u4E00", "\u9FA5" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u3007");
        XML_NAME_ALLOWED_CHARACTERS.set("\u3021", "\u3029" + 1);
        // XML Combining Character Set
        XML_NAME_ALLOWED_CHARACTERS.set("\u0300", "\u0345" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0360", "\u0361" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0483", "\u0486" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0591", "\u05A1" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u05A3", "\u05B9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u05BB", "\u05BD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u05BF");
        XML_NAME_ALLOWED_CHARACTERS.set("\u05C1", "\u05C2" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u05C4");
        XML_NAME_ALLOWED_CHARACTERS.set("\u064B", "\u0652" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0670");
        XML_NAME_ALLOWED_CHARACTERS.set("\u06D6", "\u06DC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06DD", "\u06DF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06E0", "\u06E4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06E7", "\u06E8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06EA", "\u06ED" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0901", "\u0903" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u093C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u093E", "\u094C" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u094D");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0951", "\u0954" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0962", "\u0963" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0981", "\u0983" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09BC");
        XML_NAME_ALLOWED_CHARACTERS.set("\u09BE");
        XML_NAME_ALLOWED_CHARACTERS.set("\u09BF");
        XML_NAME_ALLOWED_CHARACTERS.set("\u09C0", "\u09C4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09C7", "\u09C8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09CB", "\u09CD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09D7");
        XML_NAME_ALLOWED_CHARACTERS.set("\u09E2", "\u09E3" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A02");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A3C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A3E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A3F");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A40", "\u0A42" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A47", "\u0A48" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A4B", "\u0A4D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A70", "\u0A71" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A81", "\u0A83" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0ABC");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0ABE", "\u0AC5" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0AC7", "\u0AC9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0ACB", "\u0ACD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B01", "\u0B03" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B3C");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B3E", "\u0B43" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B47", "\u0B48" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B4B", "\u0B4D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B56", "\u0B57" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B82", "\u0B83" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BBE", "\u0BC2" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BC6", "\u0BC8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BCA", "\u0BCD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BD7");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C01", "\u0C03" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C3E", "\u0C44" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C46", "\u0C48" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C4A", "\u0C4D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C55", "\u0C56" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C82", "\u0C83" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CBE", "\u0CC4" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CC6", "\u0CC8" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CCA", "\u0CCD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CD5", "\u0CD6" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D02", "\u0D03" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D3E", "\u0D43" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D46", "\u0D48" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D4A", "\u0D4D" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D57");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E31");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E34", "\u0E3A" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E47", "\u0E4E" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EB1");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EB4", "\u0EB9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EBB", "\u0EBC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EC8", "\u0ECD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F18", "\u0F19" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F35");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F37");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F39");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F3E");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F3F");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F71", "\u0F84" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F86", "\u0F8B" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F90", "\u0F95" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F97");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F99", "\u0FAD" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0FB1", "\u0FB7" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0FB9");
        XML_NAME_ALLOWED_CHARACTERS.set("\u20D0", "\u20DC" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u20E1");
        XML_NAME_ALLOWED_CHARACTERS.set("\u302A", "\u302F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u3099");
        XML_NAME_ALLOWED_CHARACTERS.set("\u309A");
        // XML Digits
        XML_NAME_ALLOWED_CHARACTERS.set("\u0030", "\u0039" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0660", "\u0669" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u06F0", "\u06F9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0966", "\u096F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u09E6", "\u09EF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0A66", "\u0A6F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0AE6", "\u0AEF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0B66", "\u0B6F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0BE7", "\u0BEF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0C66", "\u0C6F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0CE6", "\u0CEF" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0D66", "\u0D6F" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E50", "\u0E59" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0ED0", "\u0ED9" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u0F20", "\u0F29" + 1);
        // XML Extenders
        XML_NAME_ALLOWED_CHARACTERS.set("\u00B7");
        XML_NAME_ALLOWED_CHARACTERS.set("\u02D0");
        XML_NAME_ALLOWED_CHARACTERS.set("\u02D1");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0387");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0640");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0E46");
        XML_NAME_ALLOWED_CHARACTERS.set("\u0EC6");
        XML_NAME_ALLOWED_CHARACTERS.set("\u3005");
        XML_NAME_ALLOWED_CHARACTERS.set("\u3031", "\u3035" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u309D", "\u309E" + 1);
        XML_NAME_ALLOWED_CHARACTERS.set("\u30FC", "\u30FE" + 1);
    }
    /**
     * {@inheritDoc}
     * 
     * @see org.jboss.dna.rumon.text.TextDecoder#decode(java.lang.String)
     */
    public String decode( String encodedText ) {
        if (encodedText == null) return null;
        if (encodedText.length() < 7) {
            // Not big enough to have an encoded sequence
            return encodedText;
        }
        StringBuilder sb = new StringBuilder();
        char[] digits = new char[4];
        CharacterIterator iter = new StringCharacterIterator(encodedText);
        for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
            if (c == "_") {
                // Read the next character, if there is one ...
                char next = iter.next();
                if (next == CharacterIterator.DONE) {
                    sb.append(c);
                    break;
                }
                // If the next character is not "x", then these are just regular characters ...
                if (next != "x") {
                    sb.append(c).append(next);
                    continue;
                }
                // Read the next 4 characters (digits) and another "_" character ...
                digits[0] = iter.next();
                if (digits[0] == CharacterIterator.DONE) {
                    sb.append(c).append(next);
                    break;
                }
                digits[1] = iter.next();
                if (digits[1] == CharacterIterator.DONE) {
                    sb.append(c).append(next).append(digits, 0, 1);
                    break;
                }
                digits[2] = iter.next();
                if (digits[2] == CharacterIterator.DONE) {
                    sb.append(c).append(next).append(digits, 0, 2);
                    break;
                }
                digits[3] = iter.next();
                if (digits[3] == CharacterIterator.DONE) {
                    sb.append(c).append(next).append(digits, 0, 3);
                    break;
                }
                char underscore = iter.next();
                if (underscore != "_") { // includes DONE
                    sb.append(c).append(next).append(digits, 0, 4);
                    if (underscore == CharacterIterator.DONE) break;
                    sb.append(underscore);
                    continue;
                }
                // We"ve read all 4 digits, including the trailing "_"
                // Now parse into the resulting character
                try {
                    sb.appendCodePoint(Integer.parseInt(new String(digits), 16));
                } catch (NumberFormatException e) {
                    // code was not hexadecimal, so just write out the characters as is ...
                    sb.append(c).append(next).append(digits).append(underscore);
                }
            } else {
                // Just append other characters ...
                sb.append(c);
            }
        }
        return sb.toString();
    }
    /**
     * {@inheritDoc}
     * 
     * @see org.jboss.dna.rumon.text.TextEncoder#encode(java.lang.String)
     */
    public String encode( String text ) {
        if (text == null) return null;
        if (text.length() == 0) return text;
        StringBuilder sb = new StringBuilder();
        String hex = null;
        CharacterIterator iter = new StringCharacterIterator(text);
        for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
            if (c == "_") {
                // Read the next character (if there is one) ...
                char next = iter.next();
                if (next == CharacterIterator.DONE) {
                    sb.append(c);
                    break;
                }
                // If the next character is not "x", then these are just regular characters ...
                if (next != "x") {
                    sb.append(c).append(next);
                    continue;
                }
                // The next character is "x", so write out the "_" character in encoded form ...
                sb.append("_x005f_");
                // And then write out the next character ...
                sb.append(next);
            } else if (XML_NAME_ALLOWED_CHARACTERS.get(c)) {
                // Legal characters for an XML Name ...
                sb.append(c);
            } else {
                // All other characters must be escaped with "_xHHHH_" where "HHHH" is the hex string for the code point
                hex = Integer.toHexString(c);
                // The hex string excludes the leading "0"s, so check the character values so we know how many to prepend
                if (c >= "\u0000" && c <= "\u000f") {
                    sb.append("_x000").append(hex);
                } else if (c >= "\u0010" && c <= "\u00ff") {
                    sb.append("_x00").append(hex);
                } else if (c >= "\u0100" && c <= "\u0fff") {
                    sb.append("_x0").append(hex);
                } else {
                    sb.append("_x").append(hex);
                }
                sb.append("_");
            }
        }
        return sb.toString();
    }
}





Provides a trace of the schema type information for elements and attributes in an XML document.

 
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.TypeInfoProvider;
import javax.xml.validation.ValidatorHandler;
import org.w3c.dom.TypeInfo;
import org.xml.sax.Attributes;
import org.xml.sax.DTDHandler;
import org.xml.sax.Locator;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.ParserAdapter;
import org.xml.sax.helpers.ParserFactory;
import org.xml.sax.helpers.XMLReaderFactory;
/**
 * <p>
 * Provides a trace of the schema type information for elements and attributes
 * in an XML document. This demonstrates usage of the JAXP 1.3 Validation API,
 * particuarly how to read type information from a TypeInfoProvider.
 * </p>
 * 
 * @author Michael Glavassevich, IBM
 * 
 * @version $Id: TypeInfoWriter.java 447685 2006-09-19 02:37:49Z mrglavas $
 */
public class TypeInfoWriter extends DefaultHandler {
  //
  // Constants
  //
  // feature ids
  /**
   * Schema full checking feature id
   * (http://apache.org/xml/features/validation/schema-full-checking).
   */
  protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
  /**
   * Honour all schema locations feature id
   * (http://apache.org/xml/features/honour-all-schemaLocations).
   */
  protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations";
  /**
   * Validate schema annotations feature id
   * (http://apache.org/xml/features/validate-annotations)
   */
  protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
  /**
   * Generate synthetic schema annotations feature id
   * (http://apache.org/xml/features/generate-synthetic-annotations).
   */
  protected static final String GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations";
  // default settings
  /** Default schema language (http://www.w3.org/2001/XMLSchema). */
  protected static final String DEFAULT_SCHEMA_LANGUAGE = XMLConstants.W3C_XML_SCHEMA_NS_URI;
  /** Default parser name (org.apache.xerces.parsers.SAXParser). */
  protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
  /** Default schema full checking support (false). */
  protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
  /** Default honour all schema locations (false). */
  protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false;
  /** Default validate schema annotations (false). */
  protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
  /** Default generate synthetic schema annotations (false). */
  protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false;
  //
  // Data
  //
  /** TypeInfo provider. */
  protected TypeInfoProvider fTypeInfoProvider;
  /** Print writer. */
  protected PrintWriter fOut;
  /** Indent level. */
  protected int fIndent;
  //
  // Constructors
  //
  /** Default constructor. */
  public TypeInfoWriter() {
  }
  //
  // ContentHandler and DocumentHandler methods
  //
  /** Set document locator. */
  public void setDocumentLocator(Locator locator) {
    fIndent = 0;
    printIndent();
    fOut.print("setDocumentLocator(");
    fOut.print("systemId=");
    printQuotedString(locator.getSystemId());
    fOut.print(", publicId=");
    printQuotedString(locator.getPublicId());
    fOut.println(")");
    fOut.flush();
  } // setDocumentLocator(Locator)
  /** Start document. */
  public void startDocument() throws SAXException {
    fIndent = 0;
    printIndent();
    fOut.println("startDocument()");
    fOut.flush();
    fIndent++;
  } // startDocument()
  /** Start element. */
  public void startElement(String uri, String localName, String qname, Attributes attributes)
      throws SAXException {
    TypeInfo type;
    printIndent();
    fOut.print("startElement(");
    fOut.print("name=");
    printQName(uri, localName);
    fOut.print(",");
    fOut.print("type=");
    if (fTypeInfoProvider != null && (type = fTypeInfoProvider.getElementTypeInfo()) != null) {
      printQName(type.getTypeNamespace(), type.getTypeName());
    } else {
      fOut.print("null");
    }
    fOut.print(",");
    fOut.print("attributes=");
    if (attributes == null) {
      fOut.println("null");
    } else {
      fOut.print("{");
      int length = attributes.getLength();
      for (int i = 0; i < length; i++) {
        if (i > 0) {
          fOut.print(",");
        }
        String attrURI = attributes.getURI(i);
        String attrLocalName = attributes.getLocalName(i);
        fOut.print("{");
        fOut.print("name=");
        printQName(attrURI, attrLocalName);
        fOut.print(",");
        fOut.print("type=");
        if (fTypeInfoProvider != null && (type = fTypeInfoProvider.getAttributeTypeInfo(i)) != null) {
          printQName(type.getTypeNamespace(), type.getTypeName());
        } else {
          fOut.print("null");
        }
        fOut.print(",");
        fOut.print("id=");
        fOut.print(fTypeInfoProvider != null && fTypeInfoProvider.isIdAttribute(i) ? "\"true\""
            : "\"false\"");
        fOut.print(",");
        fOut.print("specified=");
        fOut.print(fTypeInfoProvider == null || fTypeInfoProvider.isSpecified(i) ? "\"true\""
            : "\"false\"");
        fOut.print("}");
      }
      fOut.print("}");
    }
    fOut.println(")");
    fOut.flush();
    fIndent++;
  } // startElement(String,String,String,Attributes)
  /** End element. */
  public void endElement(String uri, String localName, String qname) throws SAXException {
    fIndent--;
    printIndent();
    fOut.print("endElement(");
    fOut.print("name=");
    printQName(uri, localName);
    fOut.println(")");
    fOut.flush();
  } // endElement(String,String,String)
  /** End document. */
  public void endDocument() throws SAXException {
    fIndent--;
    printIndent();
    fOut.println("endDocument()");
    fOut.flush();
  } // endDocument()
  //
  // ErrorHandler methods
  //
  /** Warning. */
  public void warning(SAXParseException ex) throws SAXException {
    printError("Warning", ex);
  } // warning(SAXParseException)
  /** Error. */
  public void error(SAXParseException ex) throws SAXException {
    printError("Error", ex);
  } // error(SAXParseException)
  /** Fatal error. */
  public void fatalError(SAXParseException ex) throws SAXException {
    printError("Fatal Error", ex);
    throw ex;
  } // fatalError(SAXParseException)
  //
  // Public methods
  //
  /** Sets the output stream for printing. */
  public void setOutput(OutputStream stream, String encoding) throws UnsupportedEncodingException {
    if (encoding == null) {
      encoding = "UTF8";
    }
    java.io.Writer writer = new OutputStreamWriter(stream, encoding);
    fOut = new PrintWriter(writer);
  } // setOutput(OutputStream,String)
  //
  // Protected methods
  //
  /** Sets the TypeInfoProvider used by this writer. */
  protected void setTypeInfoProvider(TypeInfoProvider provider) {
    fTypeInfoProvider = provider;
  }
  /** Prints the error message. */
  protected void printError(String type, SAXParseException ex) {
    System.err.print("[");
    System.err.print(type);
    System.err.print("] ");
    String systemId = ex.getSystemId();
    if (systemId != null) {
      int index = systemId.lastIndexOf("/");
      if (index != -1)
        systemId = systemId.substring(index + 1);
      System.err.print(systemId);
    }
    System.err.print(":");
    System.err.print(ex.getLineNumber());
    System.err.print(":");
    System.err.print(ex.getColumnNumber());
    System.err.print(": ");
    System.err.print(ex.getMessage());
    System.err.println();
    System.err.flush();
  } // printError(String,SAXParseException)
  /** Prints the indent. */
  protected void printIndent() {
    for (int i = 0; i < fIndent; i++) {
      fOut.print(" ");
    }
  } // printIndent()
  protected void printQName(String uri, String localName) {
    if (uri != null && uri.length() > 0) {
      printQuotedString("{" + uri + "}" + localName);
      return;
    }
    printQuotedString(localName);
  }
  /** Print quoted string. */
  protected void printQuotedString(String s) {
    if (s == null) {
      fOut.print("null");
      return;
    }
    fOut.print(""");
    fOut.print(s);
    fOut.print(""");
  } // printQuotedString(String)
  //
  // MAIN
  //
  /** Main program entry point. */
  public static void main(String[] argv) {
    // is there anything to do?
    if (argv.length == 0) {
      printUsage();
      System.exit(1);
    }
    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    // process arguments
    for (int i = 0; i < argv.length; ++i) {
      String arg = argv[i];
      if (arg.startsWith("-")) {
        String option = arg.substring(1);
        if (option.equals("l")) {
          // get schema language name
          if (++i == argv.length) {
            System.err.println("error: Missing argument to -l option.");
          } else {
            schemaLanguage = argv[i];
          }
          continue;
        }
        if (option.equals("p")) {
          // get parser name
          if (++i == argv.length) {
            System.err.println("error: Missing argument to -p option.");
            continue;
          }
          String parserName = argv[i];
          // create parser
          try {
            parser = XMLReaderFactory.createXMLReader(parserName);
          } catch (Exception e) {
            try {
              Parser sax1Parser = ParserFactory.makeParser(parserName);
              parser = new ParserAdapter(sax1Parser);
              System.err.println("warning: Features and properties not supported on SAX1 parsers.");
            } catch (Exception ex) {
              parser = null;
              System.err.println("error: Unable to instantiate parser (" + parserName + ")");
              e.printStackTrace(System.err);
              System.exit(1);
            }
          }
          continue;
        }
        if (arg.equals("-a")) {
          // process -a: schema documents
          if (schemas == null) {
            schemas = new Vector();
          }
          while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
            schemas.add(arg);
            ++i;
          }
          continue;
        }
        if (arg.equals("-i")) {
          // process -i: instance documents
          if (instances == null) {
            instances = new Vector();
          }
          while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
            instances.add(arg);
            ++i;
          }
          continue;
        }
        if (option.equalsIgnoreCase("f")) {
          schemaFullChecking = option.equals("f");
          continue;
        }
        if (option.equalsIgnoreCase("hs")) {
          honourAllSchemaLocations = option.equals("hs");
          continue;
        }
        if (option.equalsIgnoreCase("va")) {
          validateAnnotations = option.equals("va");
          continue;
        }
        if (option.equalsIgnoreCase("ga")) {
          generateSyntheticAnnotations = option.equals("ga");
          continue;
        }
        if (option.equals("h")) {
          printUsage();
          continue;
        }
        System.err.println("error: unknown option (" + option + ").");
        continue;
      }
    }
    // use default parser?
    if (parser == null) {
      // create parser
      try {
        parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
      } catch (Exception e) {
        System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
        e.printStackTrace(System.err);
        System.exit(1);
      }
    }
    try {
      // Create writer
      TypeInfoWriter writer = new TypeInfoWriter();
      writer.setOutput(System.out, "UTF8");
      // Create SchemaFactory and configure
      SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
      factory.setErrorHandler(writer);
      try {
        factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      }
      try {
        factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      }
      try {
        factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      }
      try {
        factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      }
      // Build Schema from sources
      Schema schema;
      if (schemas != null && schemas.size() > 0) {
        final int length = schemas.size();
        StreamSource[] sources = new StreamSource[length];
        for (int j = 0; j < length; ++j) {
          sources[j] = new StreamSource((String) schemas.elementAt(j));
        }
        schema = factory.newSchema(sources);
      } else {
        schema = factory.newSchema();
      }
      // Setup validator and parser
      ValidatorHandler validator = schema.newValidatorHandler();
      parser.setContentHandler(validator);
      if (validator instanceof DTDHandler) {
        parser.setDTDHandler((DTDHandler) validator);
      }
      parser.setErrorHandler(writer);
      validator.setContentHandler(writer);
      validator.setErrorHandler(writer);
      writer.setTypeInfoProvider(validator.getTypeInfoProvider());
      try {
        validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      }
      try {
        validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      }
      try {
        validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      }
      try {
        validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      }
      // Validate instance documents and print type information
      if (instances != null && instances.size() > 0) {
        final int length = instances.size();
        for (int j = 0; j < length; ++j) {
          parser.parse((String) instances.elementAt(j));
        }
      }
    } catch (SAXParseException e) {
      // ignore
    } catch (Exception e) {
      System.err.println("error: Parse error occurred - " + e.getMessage());
      if (e instanceof SAXException) {
        Exception nested = ((SAXException) e).getException();
        if (nested != null) {
          e = nested;
        }
      }
      e.printStackTrace(System.err);
    }
  } // main(String[])
  //
  // Private static methods
  //
  /** Prints the usage. */
  private static void printUsage() {
    System.err.println("usage: java jaxp.TypeInfoWriter (options) ...");
    System.err.println();
    System.err.println("options:");
    System.err.println("  -l name     Select schema language by name.");
    System.err.println("  -p name     Select parser by name.");
    System.err.println("  -a uri ...  Provide a list of schema documents");
    System.err.println("  -i uri ...  Provide a list of instance documents to validate");
    System.err.println("  -f  | -F    Turn on/off Schema full checking.");
    System.err.println("              NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -hs | -HS   Turn on/off honouring of all schema locations.");
    System.err.println("              NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -va | -VA   Turn on/off validation of schema annotations.");
    System.err.println("              NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -ga | -GA   Turn on/off generation of synthetic schema annotations.");
    System.err.println("              NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -h          This help screen.");
    System.err.println();
    System.err.println("defaults:");
    System.err.println("  Schema language:                 " + DEFAULT_SCHEMA_LANGUAGE);
    System.err.println("  Parser:                          " + DEFAULT_PARSER_NAME);
    System.err.print("  Schema full checking:            ");
    System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
    System.err.print("  Honour all schema locations:     ");
    System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off");
    System.err.print("  Validate annotations:            ");
    System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
    System.err.print("  Generate synthetic annotations:  ");
    System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off");
  } // printUsage()
} // class TypeInfoWriter





Resolve relative URIs and SystemID strings into absolute URIs

  
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */
/*
 * $Id: SystemIDResolver.java 468655 2006-10-28 07:12:06Z minchau $
 */
import java.io.File;
import java.net.URI;
import javax.xml.transform.TransformerException;

/**
 * This class is used to resolve relative URIs and SystemID 
 * strings into absolute URIs.
 *
 * <p>This is a generic utility for resolving URIs, other than the 
 * fact that it"s declared to throw TransformerException.  Please 
 * see code comments for details on how resolution is performed.</p>
 * @xsl.usage internal
 */
public class SystemIDResolver
{
  /**
   * Get an absolute URI from a given relative URI (local path). 
   * 
   * <p>The relative URI is a local filesystem path. The path can be
   * absolute or relative. If it is a relative path, it is resolved relative 
   * to the system property "user.dir" if it is available; if not (i.e. in an 
   * Applet perhaps which throws SecurityException) then we just return the
   * relative path. The space and backslash characters are also replaced to
   * generate a good absolute URI.</p>
   *
   * @param localPath The relative URI to resolve
   *
   * @return Resolved absolute URI
   */
  public static String getAbsoluteURIFromRelative(String localPath)
  {
    if (localPath == null || localPath.length() == 0)
      return "";
      
    // If the local path is a relative path, then it is resolved against
    // the "user.dir" system property.
    String absolutePath = localPath;
    if (!isAbsolutePath(localPath))
    {
      try 
      {
        absolutePath = getAbsolutePathFromRelativePath(localPath);
      }
      // user.dir not accessible from applet
      catch (SecurityException se) 
      {
        return "file:" + localPath;
      }
    }
    String urlString;
    if (null != absolutePath)
    {
      if (absolutePath.startsWith(File.separator))
        urlString = "file://" + absolutePath;
      else
        urlString = "file:///" + absolutePath;        
    }
    else
      urlString = "file:" + localPath;
    
    return replaceChars(urlString);
  }
  
  /**
   * Return an absolute path from a relative path.
   *
   * @param relativePath A relative path
   * @return The absolute path
   */
  private static String getAbsolutePathFromRelativePath(String relativePath)
  {
    return new File(relativePath).getAbsolutePath();
  }
  
  /**
   * Return true if the systemId denotes an absolute URI .
   *
   * @param systemId The systemId string
   * @return true if the systemId is an an absolute URI
   */
  public static boolean isAbsoluteURI(String systemId)
  {
     /** http://www.ietf.org/rfc/rfc2396.txt
      *   Authors should be aware that a path segment which contains a colon
      * character cannot be used as the first segment of a relative URI path
      * (e.g., "this:that"), because it would be mistaken for a scheme name.
     **/
     /** 
      * %REVIEW% Can we assume here that systemId is a valid URI?
      * It looks like we cannot ( See discussion of this common problem in 
      * Bugzilla Bug 22777 ). 
     **/
     //"fix" for Bugzilla Bug 22777
    if(isWindowsAbsolutePath(systemId)){
        return false;
     }
    
    final int fragmentIndex = systemId.indexOf("#");
    final int queryIndex = systemId.indexOf("?");
    final int slashIndex = systemId.indexOf("/");
    final int colonIndex = systemId.indexOf(":");
    
    //finding substring  before "#", "?", and "/" 
    int index = systemId.length() -1;
    if(fragmentIndex > 0) 
        index = fragmentIndex;
    if((queryIndex > 0) && (queryIndex <index)) 
        index = queryIndex;
    if((slashIndex > 0) && (slashIndex <index))
        index = slashIndex; 
    // return true if there is ":" before "#", "?", and "/"
    return ((colonIndex >0) && (colonIndex<index));
    
  }
  
  /**
   * Return true if the local path is an absolute path.
   *
   * @param systemId The path string
   * @return true if the path is absolute
   */
  public static boolean isAbsolutePath(String systemId)
  {
    if(systemId == null)
        return false;
    final File file = new File(systemId);
    return file.isAbsolute();
    
  }
  
   /**
   * Return true if the local path is a Windows absolute path.
   *
   * @param systemId The path string
   * @return true if the path is a Windows absolute path
   */
    private static boolean isWindowsAbsolutePath(String systemId)
  {
    if(!isAbsolutePath(systemId))
      return false;
    // On Windows, an absolute path starts with "[drive_letter]:\".
    if (systemId.length() > 2 
        && systemId.charAt(1) == ":"
        && Character.isLetter(systemId.charAt(0))
        && (systemId.charAt(2) == "\\" || systemId.charAt(2) == "/"))
      return true;
    else
      return false;
  }
  
  /**
   * Replace spaces with "%20" and backslashes with forward slashes in 
   * the input string to generate a well-formed URI string.
   *
   * @param str The input string
   * @return The string after conversion
   */
  private static String replaceChars(String str)
  {
    StringBuffer buf = new StringBuffer(str);
    int length = buf.length();
    for (int i = 0; i < length; i++)
    {
      char currentChar = buf.charAt(i);
      // Replace space with "%20"
      if (currentChar == " ")
      {
        buf.setCharAt(i, "%");
        buf.insert(i+1, "20");
        length = length + 2;
        i = i + 2;
      }
      // Replace backslash with forward slash
      else if (currentChar == "\\")
      {
        buf.setCharAt(i, "/");
      }
    }
    
    return buf.toString();
  }
  
  /**
   * Take a SystemID string and try to turn it into a good absolute URI.
   *
   * @param systemId A URI string, which may be absolute or relative.
   *
   * @return The resolved absolute URI
   */
  public static String getAbsoluteURI(String systemId)
  {
    String absoluteURI = systemId;
    if (isAbsoluteURI(systemId))
    {
      // Only process the systemId if it starts with "file:".
      if (systemId.startsWith("file:"))
      {
        String str = systemId.substring(5);
        
        // Resolve the absolute path if the systemId starts with "file:///"
        // or "file:/". Don"t do anything if it only starts with "file://".
        if (str != null && str.startsWith("/"))
        {
          if (str.startsWith("///") || !str.startsWith("//"))
          {
            // A Windows path containing a drive letter can be relative.
            // A Unix path starting with "file:/" is always absolute.
            int secondColonIndex = systemId.indexOf(":", 5);
            if (secondColonIndex > 0)
            {
              String localPath = systemId.substring(secondColonIndex-1);
              try {
                if (!isAbsolutePath(localPath))
                  absoluteURI = systemId.substring(0, secondColonIndex-1) + 
                                getAbsolutePathFromRelativePath(localPath);
              }
              catch (SecurityException se) {
                return systemId;
              }
            }
          }          
        }
        else
        {
          return getAbsoluteURIFromRelative(systemId.substring(5));
        }
                
        return replaceChars(absoluteURI);
      }
      else
        return systemId;
    }
    else
      return getAbsoluteURIFromRelative(systemId);
    
  }

  
}





Return the first element child with the specified qualified name.

 
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */
import java.io.OutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
 * Few simple utils to read DOM. This is originally from the Jakarta Commons
 * Modeler.
 * 
 * @author Costin Manolache
 */
public class Utils {
  /**
   * Return the first element child with the specified qualified name.
   * 
   * @param parent
   * @param ns
   * @param lp
   * @return
   */
  public static Element getFirstChildWithName(Element parent, String ns, String lp) {
      for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
          if (n instanceof Element) {
              Element e = (Element)n;
              String ens = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
              if (ns.equals(ens) && lp.equals(e.getLocalName())) {
                  return e;
              }
          }
      }
      return null;
  }
}





Use JAXP Validation API to create a validator and validate input from a DOM which contains inline schemas and multiple validation roots.

 
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
/**
 * <p>
 * A sample demonstrating how to use the JAXP 1.3 Validation API to create a
 * validator and use the validator to validate input from a DOM which contains
 * inline schemas and multiple validation roots. The output of this program
 * shows the time spent executing the Validator.validate(Source) method.
 * </p>
 * 
 * <p>
 * This class is useful as a "poor-man"s" performance tester to compare the
 * speed of various JAXP 1.3 validators with different input sources. However,
 * it is important to note that the first validation time of a validator will
 * include both VM class load time and validator initialization that would not
 * be present in subsequent validations with the same document.
 * </p>
 * 
 * <p>
 * <strong>Note:</strong> The results produced by this program should never be
 * accepted as true performance measurements.
 * </p>
 * 
 * @author Michael Glavassevich, IBM
 * 
 * @version $Id: InlineSchemaValidator.java 447685 2006-09-19 02:37:49Z mrglavas $
 */
public class InlineSchemaValidator implements ErrorHandler, NamespaceContext {
  //
  // Constants
  //
  // feature ids
  /**
   * Schema full checking feature id
   * (http://apache.org/xml/features/validation/schema-full-checking).
   */
  protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
  /**
   * Honour all schema locations feature id
   * (http://apache.org/xml/features/honour-all-schemaLocations).
   */
  protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations";
  /**
   * Validate schema annotations feature id
   * (http://apache.org/xml/features/validate-annotations)
   */
  protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
  /**
   * Generate synthetic schema annotations feature id
   * (http://apache.org/xml/features/generate-synthetic-annotations).
   */
  protected static final String GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations";
  // default settings
  /** Default schema language (http://www.w3.org/2001/XMLSchema). */
  protected static final String DEFAULT_SCHEMA_LANGUAGE = XMLConstants.W3C_XML_SCHEMA_NS_URI;
  /** Default repetition (1). */
  protected static final int DEFAULT_REPETITION = 1;
  /** Default schema full checking support (false). */
  protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
  /** Default honour all schema locations (false). */
  protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false;
  /** Default validate schema annotations (false). */
  protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
  /** Default generate synthetic schema annotations (false). */
  protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false;
  /** Default memory usage report (false). */
  protected static final boolean DEFAULT_MEMORY_USAGE = false;
  //
  // Data
  //
  /** Print writer. */
  protected PrintWriter fOut = new PrintWriter(System.out);
  /** Prefix to URI mappings for the NamespaceContext. */
  protected HashMap fPrefixToURIMappings;
  /** URI to prefix mappings for the NamespaceContext. */
  protected HashMap fURIToPrefixMappings;
  //
  // Constructors
  //
  public InlineSchemaValidator(HashMap prefixToURIMappings, HashMap uriToPrefixMappings) {
    fPrefixToURIMappings = prefixToURIMappings;
    fURIToPrefixMappings = uriToPrefixMappings;
  } // <init>(HashMap,HashMap)
  //
  // Public methods
  //
  public void validate(Validator validator, Source source, String systemId, int repetitions,
      boolean memoryUsage) {
    try {
      long timeBefore = System.currentTimeMillis();
      long memoryBefore = Runtime.getRuntime().freeMemory();
      for (int j = 0; j < repetitions; ++j) {
        validator.validate(source);
      }
      long memoryAfter = Runtime.getRuntime().freeMemory();
      long timeAfter = System.currentTimeMillis();
      long time = timeAfter - timeBefore;
      long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE;
      printResults(fOut, systemId, time, memory, repetitions);
    } catch (SAXParseException e) {
      // ignore
    } catch (Exception e) {
      System.err.println("error: Parse error occurred - " + e.getMessage());
      Exception se = e;
      if (e instanceof SAXException) {
        se = ((SAXException) e).getException();
      }
      if (se != null)
        se.printStackTrace(System.err);
      else
        e.printStackTrace(System.err);
    }
  } // validate(Validator,Source,String,int,boolean)
  /** Prints the results. */
  public void printResults(PrintWriter out, String uri, long time, long memory, int repetition) {
    // filename.xml: 631 ms
    out.print(uri);
    out.print(": ");
    if (repetition == 1) {
      out.print(time);
    } else {
      out.print(time);
      out.print("/");
      out.print(repetition);
      out.print("=");
      out.print(((float) time) / repetition);
    }
    out.print(" ms");
    if (memory != Long.MIN_VALUE) {
      out.print(", ");
      out.print(memory);
      out.print(" bytes");
    }
    out.println();
    out.flush();
  } // printResults(PrintWriter,String,long,long,int)
  //
  // ErrorHandler methods
  //
  /** Warning. */
  public void warning(SAXParseException ex) throws SAXException {
    printError("Warning", ex);
  } // warning(SAXParseException)
  /** Error. */
  public void error(SAXParseException ex) throws SAXException {
    printError("Error", ex);
  } // error(SAXParseException)
  /** Fatal error. */
  public void fatalError(SAXParseException ex) throws SAXException {
    printError("Fatal Error", ex);
    throw ex;
  } // fatalError(SAXParseException)
  //
  // NamespaceContext methods
  //
  public String getNamespaceURI(String prefix) {
    if (prefix == null) {
      throw new IllegalArgumentException("Prefix cannot be null.");
    } else if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
      return XMLConstants.XML_NS_URI;
    } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
      return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
    } else if (fPrefixToURIMappings != null) {
      String uri = (String) fPrefixToURIMappings.get(prefix);
      if (uri != null) {
        return uri;
      }
    }
    return XMLConstants.NULL_NS_URI;
  } // getNamespaceURI(String)
  public String getPrefix(String namespaceURI) {
    if (namespaceURI == null) {
      throw new IllegalArgumentException("Namespace URI cannot be null.");
    } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) {
      return XMLConstants.XML_NS_PREFIX;
    } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
      return XMLConstants.XMLNS_ATTRIBUTE;
    } else if (fURIToPrefixMappings != null) {
      HashSet prefixes = (HashSet) fURIToPrefixMappings.get(namespaceURI);
      if (prefixes != null && prefixes.size() > 0) {
        return (String) prefixes.iterator().next();
      }
    }
    return null;
  } // getPrefix(String)
  public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null) {
      throw new IllegalArgumentException("Namespace URI cannot be null.");
    } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) {
      return new Iterator() {
        boolean more = true;
        public boolean hasNext() {
          return more;
        }
        public Object next() {
          if (!hasNext()) {
            throw new NoSuchElementException();
          }
          more = false;
          return XMLConstants.XML_NS_PREFIX;
        }
        public void remove() {
          throw new UnsupportedOperationException();
        }
      };
    } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
      return new Iterator() {
        boolean more = true;
        public boolean hasNext() {
          return more;
        }
        public Object next() {
          if (!hasNext()) {
            throw new NoSuchElementException();
          }
          more = false;
          return XMLConstants.XMLNS_ATTRIBUTE;
        }
        public void remove() {
          throw new UnsupportedOperationException();
        }
      };
    } else if (fURIToPrefixMappings != null) {
      HashSet prefixes = (HashSet) fURIToPrefixMappings.get(namespaceURI);
      if (prefixes != null && prefixes.size() > 0) {
        return prefixes.iterator();
      }
    }
    return Collections.EMPTY_LIST.iterator();
  } // getPrefixes(String)
  //
  // Protected methods
  //
  /** Prints the error message. */
  protected void printError(String type, SAXParseException ex) {
    System.err.print("[");
    System.err.print(type);
    System.err.print("] ");
    String systemId = ex.getSystemId();
    if (systemId != null) {
      int index = systemId.lastIndexOf("/");
      if (index != -1)
        systemId = systemId.substring(index + 1);
      System.err.print(systemId);
    }
    System.err.print(":");
    System.err.print(ex.getLineNumber());
    System.err.print(":");
    System.err.print(ex.getColumnNumber());
    System.err.print(": ");
    System.err.print(ex.getMessage());
    System.err.println();
    System.err.flush();
  } // printError(String,SAXParseException)
  //
  // MAIN
  //
  /** Main program entry point. */
  public static void main(String[] argv) {
    // is there anything to do?
    if (argv.length == 0) {
      printUsage();
      System.exit(1);
    }
    // variables
    Vector schemas = null;
    Vector instances = null;
    HashMap prefixMappings = null;
    HashMap uriMappings = null;
    String docURI = argv[argv.length - 1];
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    int repetition = DEFAULT_REPETITION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;
    // process arguments
    for (int i = 0; i < argv.length - 1; ++i) {
      String arg = argv[i];
      if (arg.startsWith("-")) {
        String option = arg.substring(1);
        if (option.equals("l")) {
          // get schema language name
          if (++i == argv.length) {
            System.err.println("error: Missing argument to -l option.");
          } else {
            schemaLanguage = argv[i];
          }
          continue;
        }
        if (option.equals("x")) {
          if (++i == argv.length) {
            System.err.println("error: Missing argument to -x option.");
            continue;
          }
          String number = argv[i];
          try {
            int value = Integer.parseInt(number);
            if (value < 1) {
              System.err.println("error: Repetition must be at least 1.");
              continue;
            }
            repetition = value;
          } catch (NumberFormatException e) {
            System.err.println("error: invalid number (" + number + ").");
          }
          continue;
        }
        if (arg.equals("-a")) {
          // process -a: xpath expressions for schemas
          if (schemas == null) {
            schemas = new Vector();
          }
          while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
            schemas.add(arg);
            ++i;
          }
          continue;
        }
        if (arg.equals("-i")) {
          // process -i: xpath expressions for instance documents
          if (instances == null) {
            instances = new Vector();
          }
          while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
            instances.add(arg);
            ++i;
          }
          continue;
        }
        if (arg.equals("-nm")) {
          String prefix;
          String uri;
          while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-")
              && !(uri = argv[i + 2]).startsWith("-")) {
            if (prefixMappings == null) {
              prefixMappings = new HashMap();
              uriMappings = new HashMap();
            }
            prefixMappings.put(prefix, uri);
            HashSet prefixes = (HashSet) uriMappings.get(uri);
            if (prefixes == null) {
              prefixes = new HashSet();
              uriMappings.put(uri, prefixes);
            }
            prefixes.add(prefix);
            i += 2;
          }
          continue;
        }
        if (option.equalsIgnoreCase("f")) {
          schemaFullChecking = option.equals("f");
          continue;
        }
        if (option.equalsIgnoreCase("hs")) {
          honourAllSchemaLocations = option.equals("hs");
          continue;
        }
        if (option.equalsIgnoreCase("va")) {
          validateAnnotations = option.equals("va");
          continue;
        }
        if (option.equalsIgnoreCase("ga")) {
          generateSyntheticAnnotations = option.equals("ga");
          continue;
        }
        if (option.equalsIgnoreCase("m")) {
          memoryUsage = option.equals("m");
          continue;
        }
        if (option.equals("h")) {
          printUsage();
          continue;
        }
        System.err.println("error: unknown option (" + option + ").");
        continue;
      }
    }
    try {
      // Create new instance of inline schema validator.
      InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings,
          uriMappings);
      // Parse document containing schemas and validation roots
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = dbf.newDocumentBuilder();
      db.setErrorHandler(inlineSchemaValidator);
      Document doc = db.parse(docURI);
      // Create XPath factory for selecting schema and validation roots
      XPathFactory xpf = XPathFactory.newInstance();
      XPath xpath = xpf.newXPath();
      xpath.setNamespaceContext(inlineSchemaValidator);
      // Select schema roots from the DOM
      NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0];
      for (int i = 0; i < schemaNodes.length; ++i) {
        XPathExpression xpathSchema = xpath.rupile((String) schemas.elementAt(i));
        schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET);
      }
      // Select validation roots from the DOM
      NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0];
      for (int i = 0; i < instanceNodes.length; ++i) {
        XPathExpression xpathInstance = xpath.rupile((String) instances.elementAt(i));
        instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET);
      }
      // Create SchemaFactory and configure
      SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
      factory.setErrorHandler(inlineSchemaValidator);
      try {
        factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      }
      try {
        factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      }
      try {
        factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      }
      try {
        factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: SchemaFactory does not recognize feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: SchemaFactory does not support feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      }
      // Build Schema from sources
      Schema schema;
      {
        DOMSource[] sources;
        int size = 0;
        for (int i = 0; i < schemaNodes.length; ++i) {
          size += schemaNodes[i].getLength();
        }
        sources = new DOMSource[size];
        if (size == 0) {
          schema = factory.newSchema();
        } else {
          int count = 0;
          for (int i = 0; i < schemaNodes.length; ++i) {
            NodeList nodeList = schemaNodes[i];
            int nodeListLength = nodeList.getLength();
            for (int j = 0; j < nodeListLength; ++j) {
              sources[count++] = new DOMSource(nodeList.item(j));
            }
          }
          schema = factory.newSchema(sources);
        }
      }
      // Setup validator and input source.
      Validator validator = schema.newValidator();
      validator.setErrorHandler(inlineSchemaValidator);
      try {
        validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
      }
      try {
        validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
      }
      try {
        validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + VALIDATE_ANNOTATIONS_ID + ")");
      }
      try {
        validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
      } catch (SAXNotRecognizedException e) {
        System.err.println("warning: Validator does not recognize feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      } catch (SAXNotSupportedException e) {
        System.err.println("warning: Validator does not support feature ("
            + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
      }
      // Validate instance documents
      for (int i = 0; i < instanceNodes.length; ++i) {
        NodeList nodeList = instanceNodes[i];
        int nodeListLength = nodeList.getLength();
        for (int j = 0; j < nodeListLength; ++j) {
          DOMSource source = new DOMSource(nodeList.item(j));
          source.setSystemId(docURI);
          inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage);
        }
      }
    } catch (SAXParseException e) {
      // ignore
    } catch (Exception e) {
      System.err.println("error: Parse error occurred - " + e.getMessage());
      if (e instanceof SAXException) {
        Exception nested = ((SAXException) e).getException();
        if (nested != null) {
          e = nested;
        }
      }
      e.printStackTrace(System.err);
    }
  } // main(String[])
  //
  // Private static methods
  //
  /** Prints the usage. */
  private static void printUsage() {
    System.err.println("usage: java jaxp.InlineSchemaValidator (options) uri ...");
    System.err.println();
    System.err.println("options:");
    System.err.println("  -l name          Select schema language by name.");
    System.err.println("  -x number        Select number of repetitions.");
    System.err.println("  -a xpath    ...  Provide a list of XPath expressions for schema roots");
    System.err
        .println("  -i xpath    ...  Provide a list of XPath expressions for validation roots");
    System.err
        .println("  -nm pre uri ...  Provide a list of prefix to namespace URI mappings for the XPath expressions.");
    System.err.println("  -f  | -F         Turn on/off Schema full checking.");
    System.err
        .println("                   NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -hs | -HS        Turn on/off honouring of all schema locations.");
    System.err
        .println("                   NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -va | -VA        Turn on/off validation of schema annotations.");
    System.err
        .println("                   NOTE: Not supported by all schema factories and validators.");
    System.err
        .println("  -ga | -GA        Turn on/off generation of synthetic schema annotations.");
    System.err
        .println("                   NOTE: Not supported by all schema factories and validators.");
    System.err.println("  -m  | -M         Turn on/off memory usage report");
    System.err.println("  -h               This help screen.");
    System.err.println();
    System.err.println("defaults:");
    System.err.println("  Schema language:                 " + DEFAULT_SCHEMA_LANGUAGE);
    System.err.println("  Repetition:                      " + DEFAULT_REPETITION);
    System.err.print("  Schema full checking:            ");
    System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
    System.err.print("  Honour all schema locations:     ");
    System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off");
    System.err.print("  Validate annotations:            ");
    System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
    System.err.print("  Generate synthetic annotations:  ");
    System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off");
    System.err.print("  Memory:                          ");
    System.err.println(DEFAULT_MEMORY_USAGE ? "on" : "off");
    System.err.println();
    System.err.println("notes:");
    System.err
        .println("  The speed and memory results from this program should NOT be used as the");
    System.err
        .println("  basis of parser performance comparison! Real analytical methods should be");
    System.err
        .println("  used. For better results, perform multiple document validations within the");
    System.err
        .println("  same virtual machine to remove class loading from parse time and memory usage.");
  } // printUsage()
} // class InlineSchemaValidator





Validate xml against the schema

    
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class SchemaParserXerces implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    throw e;
  }
  public void error(SAXParseException e) throws SAXException {
    throw e;
  }
  public void fatalError(SAXParseException e) throws SAXException {
    throw e;
  }
  public static void main(String[] args) throws Exception {
    DOMParser d = new DOMParser();
    d.setFeature("http://xml.org/sax/features/validation", true);
    d.setFeature("http://apache.org/xml/features/validation/schema", true);
    d.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    d.setErrorHandler(new SchemaParserXerces());
    d.parse(args[0]);
    System.out.println("Parsed successfully");
  }
}





Validate xml against XML Schema

   
/*
Parser object is: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@c9ba38
Start document: 
Start element: local name: PHONEBOOK qname: PHONEBOOK uri: 
Characters:   
Start element: local name: PERSON qname: PERSON uri: 
Characters:    
Start element: local name: NAME qname: NAME uri: 
Attributes:
  Name : firstName
  Type : CDATA
  Value: Joe
  Name : lastName
  Type : CDATA
  Value: Yin
Characters: Joe
Characters:  Yin
End element: local name: NAME qname: NAME uri: 
Characters:    
Start element: local name: EMAIL qname: EMAIL uri: 
Characters: joe@yourserver.ru
End element: local name: EMAIL qname: EMAIL uri: 
Characters:    
Start element: local name: TELEPHONE qname: TELEPHONE uri: 
Characters: 202-999-9999
End element: local name: TELEPHONE qname: TELEPHONE uri: 
Characters:    
Start element: local name: WEB qname: WEB uri: 
Characters: www.jexp.ru
End element: local name: WEB qname: WEB uri: 
Characters:   
End element: local name: PERSON qname: PERSON uri: 
Characters:   
End element: local name: PHONEBOOK qname: PHONEBOOK uri: 
End document: 
 */
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class MainClass {
  public static void main(String args[])throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;
    spf.setNamespaceAware(true);
    try {
     SchemaFactory sf =
                     SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
     spf.setSchema(sf.newSchema(new SAXSource(new InputSource(new StringReader(schemaString)))));
     parser = spf.newSAXParser();
    }
    catch(SAXException e) {
      e.printStackTrace(System.err);
      System.exit(1);    
    } 
    catch(ParserConfigurationException e) {
      e.printStackTrace(System.err);
      System.exit(1);    
    }
    MySAXHandler handler = new MySAXHandler(); 
    System.out.println(schemaString);
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
  }
  static String xmlString = "<?xml version=\"1.0\"?>" +
      "<note>" +
      "<to>rtoName</to>" +
      "<from>FromName</from>" +
      "<heading>Info</heading>" +
      "<body>Message Body</body>" +
      "</note>";
  
  static String schemaString ="<?xml version=\"1.0\"?>" +
      "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
      " targetNamespace=\"http://www.jexp.ru\"" +
      " xmlns=\"http://www.jexp.ru\"" +
      " elementFormDefault=\"qualified\">" +
      "<xs:element name=\"note\">" +
      "<xs:complexType>" +
      "<xs:sequence>" +
      "<xs:element name=\"to\" type=\"xs:string\"/>" +
      "<xs:element name=\"from\" type=\"xs:string\"/>" +
      "<xs:element name=\"heading\" type=\"xs:string\"/>" +
      "<xs:element name=\"body\" type=\"xs:string\"/>" +
      "</xs:sequence>" +
                      "</xs:complexType>" +
                      "</xs:element>" +
                      "</xs:schema>";
}
class MySAXHandler extends DefaultHandler {
  public void startDocument() {
    System.out.println("Start document: ");
  }    
    public void endDocument()  {
    System.out.println("End document: ");
  }
  
  public void startElement(String uri, String localName, String qname, 
                                                               Attributes attr)
  {
    System.out.println("Start element: local name: " + localName + " qname: " 
                                                        + qname + " uri: "+uri);
    int attrCount = attr.getLength();
    if(attrCount>0) {
      System.out.println("Attributes:"); 
      for(int i = 0 ; i<attrCount ; i++) {
        System.out.println("  Name : " + attr.getQName(i)); 
        System.out.println("  Type : " + attr.getType(i)); 
        System.out.println("  Value: " + attr.getValue(i)); 
      }
    } 
  }
  
  public void endElement(String uri, String localName, String qname) {
    System.out.println("End element: local name: " + localName + " qname: "
                                                         + qname + " uri: "+uri);
  }
  
  public void characters(char[] ch, int start, int length) {
    System.out.println("Characters: " + new String(ch, start, length));
  }
  public void ignorableWhitespace(char[] ch, int start, int length) {
    System.out.println("Ignorable whitespace: " + new String(ch, start, length));
  }
  public void startPrefixMapping(String prefix, String uri) {
    System.out.println("Start \"" + prefix + "\" namespace scope. URI: " + uri); 
  }
  public void endPrefixMapping(String prefix) {
    System.out.println("End \"" + prefix + "\" namespace scope."); 
  }
  public void warning(SAXParseException spe) {
    System.out.println("Warning at line "+spe.getLineNumber());
    System.out.println(spe.getMessage());
  }
  public void fatalError(SAXParseException spe) throws SAXException {
    System.out.println("Fatal error at line "+spe.getLineNumber());
    System.out.println(spe.getMessage());
    throw spe;
  }
}





XML constants

  
// Revised from act soap
import javax.xml.namespace.QName;
import javax.xml.soap.*;
public class TMConstants {
  
  public static final String ENCODING_MECHANISMTYPE = "ACT SAAJ";
  public static final String NS_PREFIX_WSDL = "wsdl";
  public static final String NS_URI_WSDL = "http://schemas.xmlsoap.org/wsdl/";
  
  public static final String NS_XSI_TYPE_PREFIX = "xsi";
  public static final String NS_XSI_TYPE_LOCALNAME = "type";
  public static final String NS_XSI_NIL_LOCALNAME = "nil";
  public static final String ATTR_ARRAY_TYPE = "arrayType";
  public static final String URI_2001_SCHEMA_XSI =
      "http://www.w3.org/2001/XMLSchema-instance";
    public static final String URI_1999_SCHEMA_XSD =
      "http://www.w3.org/1999/XMLSchema";
  public static final String URI_2000_SCHEMA_XSD =
      "http://www.w3.org/2000/10/XMLSchema";
  public static final String URI_2001_SCHEMA_XSD =
      "http://www.w3.org/2001/XMLSchema";
  public static final String URI_DEFAULT_SCHEMA_XSD = URI_2001_SCHEMA_XSD;
  public static final String[] URIS_SCHEMA_XSD = {
      URI_2001_SCHEMA_XSD,
      URI_2000_SCHEMA_XSD,
      URI_1999_SCHEMA_XSD
  };
  public static final String URI_DEFAULT_SCHEMA_XSD_PREFIX = "xsd";
    public static final String URI_SOAP11_ENC =
      "http://schemas.xmlsoap.org/soap/encoding/";
  public static final String URI_SOAP12_ENC =
      "http://www.w3.org/2002/12/soap-encoding";
  public static final String URI_SOAP12_NOENC =
      "http://www.w3.org/2002/12/soap-envelope/encoding/none";
  public static final String URI_DEFAULT_SOAP_ENC = URI_SOAP11_ENC;
  public static final String NS_URI_XML =
      "http://www.w3.org/XML/1998/namespace";
  public static final String[] URIS_SOAP_ENC = {
      URI_SOAP11_ENC,
      URI_SOAP12_ENC,
  };
  public static final String URI_DEFAULT_SOAP_ENC_PREFIX = "soapenc";
  public static final String URI_LITERAL_ENC = "";
  public static final QName QNAME_LITERAL_ITEM = new QName(URI_LITERAL_ENC,
      "item");
  public static final String LITERAL_ITEM = "item";
    public static final String URI_ACT_SOAP = "http://act.buaa.edu.cn/encoding/";
  public static final String URI_ACT_SOAP_PREFIX = "actsoapenc";
    public static final QName XSD_STRING = new QName(URI_DEFAULT_SCHEMA_XSD,
      "string", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_BOOLEAN = new QName(URI_DEFAULT_SCHEMA_XSD,
      "boolean", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_DOUBLE = new QName(URI_DEFAULT_SCHEMA_XSD,
      "double", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_FLOAT = new QName(URI_DEFAULT_SCHEMA_XSD,
                                                  "float",
                                                  URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_INT = new QName(URI_DEFAULT_SCHEMA_XSD, "int",
                                                URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_INTEGER = new QName(URI_DEFAULT_SCHEMA_XSD,
      "integer", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_LONG = new QName(URI_DEFAULT_SCHEMA_XSD, "long",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_SHORT = new QName(URI_DEFAULT_SCHEMA_XSD,
                                                  "short",
                                                  URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_BYTE = new QName(URI_DEFAULT_SCHEMA_XSD, "byte",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_DECIMAL = new QName(URI_DEFAULT_SCHEMA_XSD,
      "decimal", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_BASE64 = new QName(URI_DEFAULT_SCHEMA_XSD,
      "base64Binary", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_HEXBIN = new QName(URI_DEFAULT_SCHEMA_XSD,
      "hexBinary", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_ANYTYPE = new QName(URI_DEFAULT_SCHEMA_XSD,
      "anyType", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_ANY = new QName(URI_DEFAULT_SCHEMA_XSD, "any",
                                                URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_QNAME = new QName(URI_DEFAULT_SCHEMA_XSD,
                                                  "QName",
                                                  URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_DATETIME = new QName(URI_DEFAULT_SCHEMA_XSD,
      "dateTime", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_DATE = new QName(URI_DEFAULT_SCHEMA_XSD, "date",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_TIME = new QName(URI_DEFAULT_SCHEMA_XSD, "time",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
      public static final QName XSD_NORMALIZEDSTRING = new QName(
      URI_2001_SCHEMA_XSD, "normalizedString", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_TOKEN = new QName(URI_2001_SCHEMA_XSD, "token",
                                                  URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_UNSIGNEDLONG = new QName(URI_2001_SCHEMA_XSD,
      "unsignedLong", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_UNSIGNEDINT = new QName(URI_2001_SCHEMA_XSD,
      "unsignedInt", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_UNSIGNEDSHORT = new QName(URI_2001_SCHEMA_XSD,
      "unsignedShort", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_UNSIGNEDBYTE = new QName(URI_2001_SCHEMA_XSD,
      "unsignedByte", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_POSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD,
      "positiveInteger", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD,
      "negativeInteger", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NONNEGATIVEINTEGER = new QName(
      URI_2001_SCHEMA_XSD, "nonNegativeInteger", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NONPOSITIVEINTEGER = new QName(
      URI_2001_SCHEMA_XSD, "nonPositiveInteger", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_YEARMONTH = new QName(URI_2001_SCHEMA_XSD,
      "gYearMonth", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_MONTHDAY = new QName(URI_2001_SCHEMA_XSD,
      "gMonthDay", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_YEAR = new QName(URI_2001_SCHEMA_XSD, "gYear",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_MONTH = new QName(URI_2001_SCHEMA_XSD, "gMonth",
                                                  URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_DAY = new QName(URI_2001_SCHEMA_XSD, "gDay",
                                                URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_DURATION = new QName(URI_2001_SCHEMA_XSD,
      "duration", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NAME = new QName(URI_2001_SCHEMA_XSD, "Name",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NCNAME = new QName(URI_2001_SCHEMA_XSD,
      "NCName", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NMTOKEN = new QName(URI_2001_SCHEMA_XSD,
      "NMTOKEN", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NMTOKENS = new QName(URI_2001_SCHEMA_XSD,
      "NMTOKENS", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_NOTATION = new QName(URI_2001_SCHEMA_XSD,
      "NOTATION", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_ENTITY = new QName(URI_2001_SCHEMA_XSD,
      "ENTITY", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_ENTITIES = new QName(URI_2001_SCHEMA_XSD,
      "ENTITIES", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_IDREF = new QName(URI_2001_SCHEMA_XSD, "IDREF",
                                                  URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_IDREFS = new QName(URI_2001_SCHEMA_XSD,
      "IDREFS", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_ANYURI = new QName(URI_2001_SCHEMA_XSD,
      "anyURI", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_LANGUAGE = new QName(URI_2001_SCHEMA_XSD,
      "language", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_ID = new QName(URI_2001_SCHEMA_XSD, "ID",
                                               URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XSD_SCHEMA = new QName(URI_2001_SCHEMA_XSD,
      "schema", URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName XML_LANG = new QName(URI_2001_SCHEMA_XSD, "lang",
                                                 URI_DEFAULT_SCHEMA_XSD_PREFIX);
  public static final QName SOAP_BASE64 = new QName(URI_DEFAULT_SOAP_ENC,
      "base64", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_BASE64BINARY = new QName(URI_DEFAULT_SOAP_ENC,
      "base64Binary", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_STRING = new QName(URI_DEFAULT_SOAP_ENC,
      "string", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_BOOLEAN = new QName(URI_DEFAULT_SOAP_ENC,
      "boolean", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_DOUBLE = new QName(URI_DEFAULT_SOAP_ENC,
      "double", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_FLOAT = new QName(URI_DEFAULT_SOAP_ENC,
      "float", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_INT = new QName(URI_DEFAULT_SOAP_ENC, "int",
                                                 URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_LONG = new QName(URI_DEFAULT_SOAP_ENC, "long",
                                                  URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_SHORT = new QName(URI_DEFAULT_SOAP_ENC,
      "short", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_BYTE = new QName(URI_DEFAULT_SOAP_ENC, "byte",
                                                  URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_INTEGER = new QName(URI_DEFAULT_SOAP_ENC,
      "integer", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_DECIMAL = new QName(URI_DEFAULT_SOAP_ENC,
      "decimal", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_ARRAY = new QName(URI_DEFAULT_SOAP_ENC,
      "Array", URI_DEFAULT_SOAP_ENC_PREFIX);
  public static final QName SOAP_ARRAY12 = new QName(URI_SOAP12_ENC, "Array",
      URI_DEFAULT_SOAP_ENC_PREFIX);
    public static final QName QNAME_TYPE_COLLECTION = new QName(
      URI_ACT_SOAP, "collection", URI_ACT_SOAP_PREFIX);
  public static final QName QNAME_TYPE_LIST = new QName(URI_ACT_SOAP,
      "List", URI_ACT_SOAP_PREFIX);
  public static final QName QNAME_TYPE_ARRAY_LIST = new QName(
      URI_ACT_SOAP, "arrayList", URI_ACT_SOAP_PREFIX);
  public static final QName QNAME_TYPE_DATAHANDLER = new QName(URI_ACT_SOAP,
    "DataHandler", URI_ACT_SOAP_PREFIX);
  public static final QName SOAP_MAP = new QName(URI_ACT_SOAP, "Map",
                                                 URI_ACT_SOAP_PREFIX);
  public static final QName SOAP_VECTOR = new QName(URI_ACT_SOAP,
      "Vector", URI_ACT_SOAP_PREFIX);
  public static final String ANYCONTENT = "_any";
  public static final QName QNAME_MAP_ITEM = new QName("", "item");
  public static final QName QNAME_MAP_KEY = new QName("", "key");
  public static final QName QNAME_MAP_VALUE = new QName("", "value");
  public static final String DEFAULT_ENCODINGSTYLE =
      "http://schemas.xmlsoap.org/soap/encoding/";
  
  public static final String SCHEMA = "schema";
  public static final String SCHEMA_COMPLEXTYPE = "complexType";
  public static final String SCHEMA_SIMPLETYPE = "simpleType";
  public static final String SCHEMA_RESTRICTION = "restriction";
  public static final String SCHEMA_BASE = "base";
  public static final String SCHEMA_NAME = "name";
  public static final String SCHEMA_SEQUENCE = "sequence";
  public static final String SCHEMA_ELEMENT = "element";
  public static final String SCHEMA_ITEM = "item";
  public static final String SCHEMA_MINOCCURS = "minOccurs";
  public static final String SCHEMA_MAXOCCURS = "maxOccurs";
  public static final String SCHEMA_UNBOUNDED = "unbounded";
  public static final String SCHEMA_0 = "0";
  public static final String SCHEMA_TYPE = "type";
  public static final String SCHEMA_ANYTYPE = URI_DEFAULT_SCHEMA_XSD_PREFIX +
      ":anyType";
  public static final String SCHEMA_NILLABLE = "nillable";
  public static final String TARGET_NAMESPACE = "targetNamespace";
  public static SOAPFactory SOAPFACTORY_INSTANCE = null;
  static {
    try {
      System.setProperty("javax.xml.soap.SOAPFactory",
                         "org.act.soap.message.ver1_1.SOAPFactory1_1Impl");
      SOAPFACTORY_INSTANCE = SOAPFactory.newInstance();
    }
    catch (Exception ex) {}
  }
  public static Name NAME_XSITYPE = null;
  static {
    try {
      NAME_XSITYPE = SOAPFACTORY_INSTANCE.createName(TMConstants.
          NS_XSI_TYPE_LOCALNAME,
          TMConstants.NS_XSI_TYPE_PREFIX,
          TMConstants.URI_2001_SCHEMA_XSI);
    }
    catch (Exception ex) {}
  }
  public static Name NAME_NIL = null;
  static {
    try {
      NAME_NIL = SOAPFACTORY_INSTANCE.createName(TMConstants.
                                                 NS_XSI_NIL_LOCALNAME,
                                                 TMConstants.NS_XSI_TYPE_PREFIX,
                                                 TMConstants.
                                                 URI_2001_SCHEMA_XSI);
    }
    catch (Exception ex) {}
  }
  public static Name NAME_SOAPENCARRAY_TYPE = null;
  static {
    try {
      NAME_SOAPENCARRAY_TYPE = SOAPFACTORY_INSTANCE.createName(
          TMConstants.ATTR_ARRAY_TYPE,
          TMConstants.URI_DEFAULT_SOAP_ENC_PREFIX,
          TMConstants.URI_DEFAULT_SOAP_ENC);
    }
    catch (Exception ex) {}
  }
}