Java/XML/DOM Document

Материал из Java эксперт
Перейти к: навигация, поиск

Copy an XML document

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
  /**
   * Copy an XML document, adding it as a child of the target document root
   * @param source Document to copy
   * @param target Document to contain copy
   */
  public static void copyDocument(Document source, Document target)
  {
    Node node = target.importNode(source.getDocumentElement(), true);
    target.getDocumentElement().appendChild(node);
  }

}





Create Document with root QName

  
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * http://www.netbeans.org/cddl-gplv2.html
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 * specific language governing permissions and limitations under the
 * License.  When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the GPL Version 2 section of the License file that
 * accompanied this code. If applicable, add the following below the
 * License Header, with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Contributor(s):
 *
 * The Original Software is NetBeans. The Initial Developer of the Original
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
 * Microsystems, Inc. All Rights Reserved.
 *
 * If you wish your version of this file to be governed by only the CDDL
 * or only the GPL Version 2, indicate your decision by adding
 * "[Contributor] elects to include this software in this distribution
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
 * single choice of license, a recipient has the option to distribute
 * your version of this file under either the CDDL, the GPL Version 2 or
 * to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL
 * Version 2 license, then the option applies only if the new code is
 * made subject to such option by the copyright holder.
 */
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
/**
 * Utility class collecting library methods related to XML processing. Stolen
 * from nbbuild/antsrc and openide/.../xml.
 * 
 * @author Petr Kuzel, Jesse Glick
 */
public final class XMLUtil {

  public static Document createDocument(String rootQName) throws DOMException {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
          return factory.newDocumentBuilder ().getDOMImplementation ().createDocument (null, rootQName, null);
      } catch (ParserConfigurationException ex) {
          throw (DOMException)new DOMException(DOMException.NOT_SUPPORTED_ERR, "Cannot create parser").initCause(ex); // NOI18N
      }
  }
}





Create DOM Document out of string

  


import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class Main {
  public static Document load(String xml) throws Exception {
    DocumentBuilder builder = getDocumentBuilder();         
    Document document = builder.parse(new InputSource(new StringReader(xml)));
    return document;
}
  public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    return builder;
}
}





Create Empty DOM Document

  
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Document newEmptyDocument() {
    DocumentBuilderFactory factory = null;
    DocumentBuilder builder = null;
    Document ret;
    try {
      factory = DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
    ret = builder.newDocument();
    return ret;
  }
}





Displays a DOM document in a tree control.

  
/*
 * 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.Serializable;
import java.util.Hashtable;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * Displays a DOM document in a tree control.
 * 
 * @author Andy Clark, IBM
 * @version $Id: DOMTree.java 447689 2006-09-19 02:40:36Z mrglavas $
 */
public class DOMTree extends JTree {
  private static final long serialVersionUID = 3977582510937224497L;
  //
  // Constructors
  //
  /** Default constructor. */
  public DOMTree() {
    this(null);
  }
  /** Constructs a tree with the specified document. */
  public DOMTree(Document document) {
    super(new Model());
    // set tree properties
    setRootVisible(false);
    // set properties
    setDocument(document);
  } // <init>()
  //
  // Public methods
  //
  /** Sets the document. */
  public void setDocument(Document document) {
    ((Model) getModel()).setDocument(document);
    expandRow(0);
  }
  /** Returns the document. */
  public Document getDocument() {
    return ((Model) getModel()).getDocument();
  }
  /** get the org.w3c.Node for a MutableTreeNode. */
  public Node getNode(Object treeNode) {
    return ((Model) getModel()).getNode(treeNode);
  }
  //
  // Classes
  //
  /**
   * DOM tree model.
   * 
   * @author Andy Clark, IBM
   * @version
   */
  static class Model extends DefaultTreeModel implements Serializable {
    private static final long serialVersionUID = 3257286915924571186L;
    //
    // Data
    //
    /** Document. */
    private Document document;
    /** Node Map. */
    private Hashtable nodeMap = new Hashtable();
    //
    // Constructors
    //
    /** Default constructor. */
    public Model() {
      this(null);
    }
    /** Constructs a model from the specified document. */
    public Model(Document document) {
      super(new DefaultMutableTreeNode());
      setDocument(document);
    }
    //
    // Public methods
    //
    /** Sets the document. */
    public synchronized void setDocument(Document document) {
      // save document
      this.document = document;
      // clear tree and re-populate
      ((DefaultMutableTreeNode) getRoot()).removeAllChildren();
      nodeMap.clear();
      buildTree();
      fireTreeStructureChanged(this, new Object[] { getRoot() }, new int[0], new Object[0]);
    } // setDocument(Document)
    /** Returns the document. */
    public Document getDocument() {
      return document;
    }
    /** get the org.w3c.Node for a MutableTreeNode. */
    public Node getNode(Object treeNode) {
      return (Node) nodeMap.get(treeNode);
    }
    //
    // Private methods
    //
    /** Builds the tree. */
    private void buildTree() {
      // is there anything to do?
      if (document == null) {
        return;
      }
      // iterate over children of this node
      NodeList nodes = document.getChildNodes();
      int len = (nodes != null) ? nodes.getLength() : 0;
      MutableTreeNode root = (MutableTreeNode) getRoot();
      for (int i = 0; i < len; i++) {
        Node node = nodes.item(i);
        switch (node.getNodeType()) {
        case Node.DOCUMENT_NODE: {
          root = insertDocumentNode(node, root);
          break;
        }
        case Node.ELEMENT_NODE: {
          insertElementNode(node, root);
          break;
        }
        default: // ignore
        } // switch
      } // for
    } // buildTree()
    /** Inserts a node and returns a reference to the new node. */
    private MutableTreeNode insertNode(String what, MutableTreeNode where) {
      MutableTreeNode node = new DefaultMutableTreeNode(what);
      insertNodeInto(node, where, where.getChildCount());
      return node;
    } // insertNode(Node,MutableTreeNode):MutableTreeNode
    /** Inserts the document node. */
    private MutableTreeNode insertDocumentNode(Node what, MutableTreeNode where) {
      MutableTreeNode treeNode = insertNode("<" + what.getNodeName() + ">", where);
      nodeMap.put(treeNode, what);
      return treeNode;
    }
    /** Inserts an element node. */
    private MutableTreeNode insertElementNode(Node what, MutableTreeNode where) {
      // build up name
      StringBuffer name = new StringBuffer();
      name.append("<");
      name.append(what.getNodeName());
      NamedNodeMap attrs = what.getAttributes();
      int attrCount = (attrs != null) ? attrs.getLength() : 0;
      for (int i = 0; i < attrCount; i++) {
        Node attr = attrs.item(i);
        name.append(" ");
        name.append(attr.getNodeName());
        name.append("=\"");
        name.append(attr.getNodeValue());
        name.append(""");
      }
      name.append(">");
      // insert element node
      MutableTreeNode element = insertNode(name.toString(), where);
      nodeMap.put(element, what);
      // gather up attributes and children nodes
      NodeList children = what.getChildNodes();
      int len = (children != null) ? children.getLength() : 0;
      for (int i = 0; i < len; i++) {
        Node node = children.item(i);
        switch (node.getNodeType()) {
        case Node.CDATA_SECTION_NODE: {
          insertCDataSectionNode(node, element); // Add a Section Node
          break;
        }
        case Node.TEXT_NODE: {
          insertTextNode(node, element);
          break;
        }
        case Node.ELEMENT_NODE: {
          insertElementNode(node, element);
          break;
        }
        }
      }
      return element;
    } // insertElementNode(Node,MutableTreeNode):MutableTreeNode
    /** Inserts a text node. */
    private MutableTreeNode insertTextNode(Node what, MutableTreeNode where) {
      String value = what.getNodeValue().trim();
      if (value.length() > 0) {
        MutableTreeNode treeNode = insertNode(value, where);
        nodeMap.put(treeNode, what);
        return treeNode;
      }
      return null;
    }
    /** Inserts a CData Section Node. */
    private MutableTreeNode insertCDataSectionNode(Node what, MutableTreeNode where) {
      StringBuffer CSectionBfr = new StringBuffer();
 
      CSectionBfr.append(what.getNodeValue());
      if (CSectionBfr.length() > 0) {
        MutableTreeNode treeNode = insertNode(CSectionBfr.toString(), where);
        nodeMap.put(treeNode, what);
        return treeNode;
      }
      return null;
    }
  } // class Model
} // class DOMTree





Document To String

 
/*
 * Copyright  2003-2008 The Apache Software Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
  public static void ElementToStream(Element element, OutputStream out) {
    try {
      DOMSource source = new DOMSource(element);
      StreamResult result = new StreamResult(out);
      TransformerFactory transFactory = TransformerFactory.newInstance();
      Transformer transformer = transFactory.newTransformer();
      transformer.transform(source, result);
    } catch (Exception ex) {
    }
  }
  public static String DocumentToString(Document doc) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ElementToStream(doc.getDocumentElement(), baos);
    return new String(baos.toByteArray());
  }
}





get Document Element from a file

  
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
 * 
 * @author Abey Mullassery
 * 
 */
public class Main {

  public static Element getDocumentElement(File fileName)
    throws Exception {
    try {
      Document doc = getDocumentBuilder().parse(fileName);
      return doc.getDocumentElement();
    } catch (Exception se) {
      return null;
    }
  }
  /**
   * Returns a default DocumentBuilder instance or throws an
   * ExceptionInInitializerError if it can"t be created.
   *
   * @return a default DocumentBuilder instance.
   */
  public static DocumentBuilder getDocumentBuilder() throws Exception {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setIgnoringComments(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setValidating(false);
      return dbf.newDocumentBuilder();
    } catch (Exception exc) {
      throw new Exception(exc.getMessage());
    }
  }
}





load Document by element

  
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
 * 
 * @author Abey Mullassery
 * 
 */
public class Main {
  public static Element loadDocument(File f, String defElement)
  throws Exception {
  Document doc = null;
  try {
    doc = getDocumentBuilder().parse(f);
    return doc.getDocumentElement();
  } catch (Exception se) {
    if (defElement != null)
      return getDocumentBuilder().newDocument().createElement(
        defElement);
    throw new Exception(se.getMessage());
  }
}
  /**
   * Returns a default DocumentBuilder instance or throws an
   * ExceptionInInitializerError if it can"t be created.
   *
   * @return a default DocumentBuilder instance.
   */
  public static DocumentBuilder getDocumentBuilder() throws Exception {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setIgnoringComments(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setValidating(false);
      return dbf.newDocumentBuilder();
    } catch (Exception exc) {
      throw new Exception(exc.getMessage());
    }
  }
}





load Document from InputStream

  
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
import java.io.File;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
 * 
 * @author Abey Mullassery
 * 
 */
public class Main {

  public static Element loadDocument(InputStream in, String defElement)
  throws Exception {
  Document doc = null;
  try {
    doc = getDocumentBuilder().parse(in);
    return doc.getDocumentElement();
  } catch (Exception se) {
    if (defElement != null)
      return getDocumentBuilder().newDocument().createElement(
        defElement);
    throw new Exception(se.getMessage());
  }
}
  /**
   * Returns a default DocumentBuilder instance or throws an
   * ExceptionInInitializerError if it can"t be created.
   *
   * @return a default DocumentBuilder instance.
   */
  public static DocumentBuilder getDocumentBuilder() throws Exception {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setIgnoringComments(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setValidating(false);
      return dbf.newDocumentBuilder();
    } catch (Exception exc) {
      throw new Exception(exc.getMessage());
    }
  }
}





New Document From InputStream

  
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Document newDocumentFromInputStream(InputStream in) {
    DocumentBuilderFactory factory = null;
    DocumentBuilder builder = null;
    Document ret = null;
    try {
      factory = DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
    try {
      ret = builder.parse(new InputSource(in));
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ret;
  }
}





New Document From String

  
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Document newDocumentFromString(String xmlString) {
    DocumentBuilderFactory factory = null;
    DocumentBuilder builder = null;
    Document ret = null;
    try {
      factory = DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
    try {
      ret = builder.parse(new InputSource(new StringReader(xmlString)));
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ret;
  }
}





Read Xml from InputStream and return 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.IOException;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
 * Few simple utils to read DOM. This is originally from the Jakarta Commons
 * Modeler.
 * 
 * @author Costin Manolache
 */
public class Utils {
  /**
   * Read XML as DOM.
   */
  public static Document readXml(InputStream is) throws SAXException, IOException,
      ParserConfigurationException {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setValidating(false);
      dbf.setIgnoringComments(false);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setNamespaceAware(true);
      // dbf.setCoalescing(true);
      // dbf.setExpandEntityReferences(true);
      DocumentBuilder db = null;
      db = dbf.newDocumentBuilder();
      db.setEntityResolver(new NullResolver());
      // db.setErrorHandler( new MyErrorHandler());
      return db.parse(is);
  }
}
class NullResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException,
      IOException {
    return new InputSource(new StringReader(""));
  }
}





Read Xml from Reader and return 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.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
 * Few simple utils to read DOM. This is originally from the Jakarta Commons
 * Modeler.
 * 
 * @author Costin Manolache
 */
public class Utils {
  public static Document readXml(Reader is) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);
    // dbf.setCoalescing(true);
    // dbf.setExpandEntityReferences(true);
    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    // db.setErrorHandler( new MyErrorHandler());
    InputSource ips = new InputSource(is);
    return db.parse(ips);
}
}
class NullResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException,
      IOException {
    return new InputSource(new StringReader(""));
  }
}





Return a new document, ready to populate

 
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
public class Utils {
  private static DocumentBuilderFactory dbf;
  private static Queue builders = new ConcurrentLinkedQueue();
  public static DocumentBuilder getBuilder() throws ParserConfigurationException {
    DocumentBuilder builder = (DocumentBuilder) builders.poll();
    if (builder == null) {
      if (dbf == null) {
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
      }
      builder = dbf.newDocumentBuilder();
    }
    return builder;
  }
  public static void releaseBuilder(DocumentBuilder builder) {
    builders.add(builder);
  }
  /**
   * Return a new document, ready to populate.
   * 
   * @return
   * @throws ParserConfigurationException
   */
  public static Document newDocument() throws ParserConfigurationException {
    DocumentBuilder builder = getBuilder();
    Document doc = builder.newDocument();
    releaseBuilder(builder);
    return doc;
  }
}





Start a new XML Document

  
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
  /**
   * Start a new XML Document.
   * @param rootName The name of the Document root Element (created here)
   * @return the Document
   * @throws DomException
   */
  public static Document createXmlDocument(String rootName)  {
      Document  document  = getXmlDocumentBuilder().newDocument();
      Element   root      = document.createElement(rootName);
      document.appendChild(root);
      return document;
  
  }
  /**
   * Get a DOM Document builder.
   * @return The DocumentBuilder
   * @throws DomException
   */
  public static DocumentBuilder getXmlDocumentBuilder() {
    try {
      DocumentBuilderFactory factory;
      factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(false);
      return factory.newDocumentBuilder();
    } catch (Exception e) {
      
    }
    return null;
  }
}





Utility class to print out DOM

 
/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and Others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Kentarou FUKUDA - initial API and implementation
 *******************************************************************************/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.html.HTMLTitleElement;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;
/**
 * Utility class to print out DOM
 */
@SuppressWarnings("nls")
public class DomPrintUtil {
  /**
   * Default encoding of this utility. (UTF8)
   */
  public static final String UTF8 = "UTF8";
  private static final String LINE_SEP = System.getProperty("line.separator");
  private static final String EMPTY_STR = "";
  private static final String LT = "<";
  private static final String GT = ">";
  private static final String AMP = "&";
  private static final String QUAT = "\"";
  private static final String SINGLE_QUAT = """;
  private static final String ESC_LT = "&lt;";
  private static final String ESC_GT = "&gt;";
  private static final String ESC_AMP = "&amp;";
  private Document document;
  private int whatToShow = NodeFilter.SHOW_ALL;
  private NodeFilter nodeFilter = null;
  private boolean entityReferenceExpansion = false;
  private boolean indent = true;
  private boolean escapeTagBracket = false;
  private AttributeFilter attrFilter = null;
  /**
   * AttributeFilter defines the behavior of a filter that is used for
   * converting attributes of each Element into String.
   */
  public interface AttributeFilter {
    /**
     * Check whether a specified attribute is converted into String.
     * 
     * @param element
     *            the target Element
     * @param attr
     *            the target attribute
     * @return true to print the attribute, false to ignore the attribute
     */
    public boolean acceptNode(Element element, Node attr);
  }
  /**
   * Constructor of DOM print utility.
   * 
   * @param document
   *            the target document
   */
  public DomPrintUtil(Document document) {
    this.document = document;
  }
  private String getXMLString(String targetS) {
    return targetS.replaceAll(AMP, ESC_AMP).replaceAll(LT, ESC_LT)
        .replaceAll(GT, ESC_GT);
  }
  private String getAttributeString(Element element, Node attr) {
    if (null == attrFilter || attrFilter.acceptNode(element, attr)) {
      String value = getXMLString(attr.getNodeValue());
      String quat = QUAT;
      if (value.indexOf(QUAT) > 0) {
        quat = SINGLE_QUAT;
      }
      return " " + attr.getNodeName() + "=" + quat + value + quat;
    }
    return EMPTY_STR;
  }
  private boolean checkNewLine(Node target) {
    if (indent && target.hasChildNodes()) {
      short type = target.getFirstChild().getNodeType();
      if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) {
        return false;
      }
      return true;
    }
    return false;
  }
  /**
   * Returns XML text converted from the target DOM
   * 
   * @return String format XML converted from the target DOM
   */
  public String toXMLString() {
    StringBuffer tmpSB = new StringBuffer(8192);
    TreeWalkerImpl treeWalker = new TreeWalkerImpl(document, whatToShow,
        nodeFilter, entityReferenceExpansion);
    String lt = escapeTagBracket ? ESC_LT : LT;
    String gt = escapeTagBracket ? ESC_GT : GT;
    String line_sep = indent ? LINE_SEP : EMPTY_STR;
    Node tmpN = treeWalker.nextNode();
    boolean prevIsText = false;
    String indentS = EMPTY_STR;
    while (tmpN != null) {
      short type = tmpN.getNodeType();
      switch (type) {
      case Node.ELEMENT_NODE:
        if (prevIsText) {
          tmpSB.append(line_sep);
        }
        tmpSB.append(indentS + lt + tmpN.getNodeName());
        NamedNodeMap attrs = tmpN.getAttributes();
        int len = attrs.getLength();
        for (int i = 0; i < len; i++) {
          Node attr = attrs.item(i);
          String value = attr.getNodeValue();
          if (null != value) {
            tmpSB.append(getAttributeString((Element) tmpN, attr));
          }
        }
        if (tmpN instanceof HTMLTitleElement && !tmpN.hasChildNodes()) {
          tmpSB.append(gt + ((HTMLTitleElement) tmpN).getText());
          prevIsText = true;
        } else if (checkNewLine(tmpN)) {
          tmpSB.append(gt + line_sep);
          prevIsText = false;
        } else {
          tmpSB.append(gt);
          prevIsText = true;
        }
        break;
      case Node.TEXT_NODE:
        if (!prevIsText) {
          tmpSB.append(indentS);
        }
        tmpSB.append(getXMLString(tmpN.getNodeValue()));
        prevIsText = true;
        break;
      case Node.ruMENT_NODE:
        String comment;
        if (escapeTagBracket) {
          comment = getXMLString(tmpN.getNodeValue());
        } else {
          comment = tmpN.getNodeValue();
        }
        tmpSB.append(line_sep + indentS + lt + "!--" + comment + "--"
            + gt + line_sep);
        prevIsText = false;
        break;
      case Node.CDATA_SECTION_NODE:
        tmpSB.append(line_sep + indentS + lt + "!CDATA["
            + tmpN.getNodeValue() + "]]" + line_sep);
        break;
      case Node.DOCUMENT_TYPE_NODE:
        if (tmpN instanceof DocumentType) {
          DocumentType docType = (DocumentType) tmpN;
          String pubId = docType.getPublicId();
          String sysId = docType.getSystemId();
          if (null != pubId && pubId.length() > 0) {
            if (null != sysId && sysId.length() > 0) {
              tmpSB.append(lt + "!DOCTYPE " + docType.getName()
                  + " PUBLIC \"" + pubId + " \"" + sysId
                  + "\">" + line_sep);
            } else {
              tmpSB.append(lt + "!DOCTYPE " + docType.getName()
                  + " PUBLIC \"" + pubId + "\">" + line_sep);
            }
          } else {
            tmpSB.append(lt + "!DOCTYPE " + docType.getName()
                + " SYSTEM \"" + docType.getSystemId() + "\">"
                + line_sep);
          }
        } else {
          System.out
              .println("Document Type node does not implement DocumentType: "
                  + tmpN);
        }
        break;
      default:
        System.out.println(tmpN.getNodeType() + " : "
            + tmpN.getNodeName());
      }
      Node next = treeWalker.firstChild();
      if (null != next) {
        if (indent && type == Node.ELEMENT_NODE) {
          indentS = indentS + " ";
        }
        tmpN = next;
        continue;
      }
      if (tmpN.getNodeType() == Node.ELEMENT_NODE) {
        tmpSB.append(lt + "/" + tmpN.getNodeName() + gt + line_sep);
        prevIsText = false;
      }
      next = treeWalker.nextSibling();
      if (null != next) {
        tmpN = next;
        continue;
      }
      tmpN = null;
      next = treeWalker.parentNode();
      while (null != next) {
        if (next.getNodeType() == Node.ELEMENT_NODE) {
          if (indent) {
            if (indentS.length() > 0) {
              indentS = indentS.substring(1);
            } else {
              System.err.println("indent: " + next.getNodeName()
                  + " " + next);
            }
          }
          tmpSB.append(line_sep + indentS + lt + "/"
              + next.getNodeName() + gt + line_sep);
          prevIsText = false;
        }
        next = treeWalker.nextSibling();
        if (null != next) {
          tmpN = next;
          break;
        }
        next = treeWalker.parentNode();
      }
    }
    return tmpSB.toString();
  }
  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return toXMLString();
  }
  /**
   * Set whatToShow attribute to TreeWalker used in the utility.
   * 
   * @param whatToShow
   *            the attribute determines which types of node are presented via
   *            the TreeWalker. The values are defined in the NodeFilter
   *            interface.
   * @see TreeWalkerImpl
   */
  public void setWhatToShow(int whatToShow) {
    this.whatToShow = whatToShow;
  }
  /**
   * Set NodeFilter to TreeWalker used in the utility.
   * 
   * @param nodeFilter
   *            the filter used to screen nodes
   * @see TreeWalkerImpl
   */
  public void setNodeFilter(NodeFilter nodeFilter) {
    this.nodeFilter = nodeFilter;
  }
  /**
   * Set the entity reference expansion flag to TreeWalker used in the
   * utility.
   * 
   * @param entityReferenceExpansion
   *            the flag to determine whether the children of entity reference
   *            nodes are visible to TreeWalker.
   * @see TreeWalkerImpl
   */
  public void setEntityReferenceExpansion(boolean entityReferenceExpansion) {
    this.entityReferenceExpansion = entityReferenceExpansion;
  }
  /**
   * Set the number of space characters used for indent
   * 
   * @param indent
   *            the number of space characters used for indent
   */
  public void setIndent(boolean indent) {
    this.indent = indent;
  }
  /**
   * Determine to escape Tag bracket ("<",">") or not. Please set true if you
   * want to print out DOM into &lt;pre&gt; section of HTML.
   * 
   * @param escapeTagBracket
   *            if true, print Tag bracket as escaped format ({@literal "&lt;",
   *            "&gt;"})
   * 
   */
  public void setEscapeTagBracket(boolean escapeTagBracket) {
    this.escapeTagBracket = escapeTagBracket;
  }
  /**
   * Set AttributeFilter to define the behavior for printing attributes of
   * each Element.
   * 
   * @param attrFilter
   *            the AttributeFilter to set
   */
  public void setAttrFilter(AttributeFilter attrFilter) {
    this.attrFilter = attrFilter;
  }
  /**
   * Print out the target Document.
   * 
   * @param filePath
   *            the target file path
   * @throws IOException
   */
  public void writeToFile(String filePath) throws IOException {
    writeToFile(new File(filePath), UTF8);
  }
  /**
   * Print out the target Document.
   * 
   * @param file
   *            the target File
   * @throws IOException
   */
  public void writeToFile(File file) throws IOException {
    writeToFile(file, UTF8);
  }
  /**
   * Print out the target Document in specified encoding
   * 
   * @param filePath
   *            the target file path
   * @param encode
   *            the target encoding
   * @throws IOException
   */
  public void writeToFile(String filePath, String encode) throws IOException {
    writeToFile(new File(filePath), encode);
  }
  /**
   * Print out the target Document in specified encoding
   * 
   * @param file
   *            the target file
   * @param encode
   *            the target encoding
   * @throws IOException
   */
  public void writeToFile(File file, String encode) throws IOException {
    PrintWriter tmpPW = new PrintWriter(new OutputStreamWriter(
        new FileOutputStream(file), encode));
    tmpPW.println(toXMLString());
    tmpPW.flush();
    tmpPW.close();
  }
}
/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and Others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Kentarou FUKUDA - initial API and implementation
 *******************************************************************************/
class TreeWalkerImpl implements TreeWalker {
  private Node walkerRoot;
  private Node current;
  private int whatToShow;
  private NodeFilter filter;
  private NodeFilter defaultFilter;
  private boolean entitiyReferenceExpansion;
  private boolean noFilter = true;
  public TreeWalkerImpl(Node root, int whatToShow, NodeFilter filter,
      boolean entityReferenceExpansion) throws DOMException {
    if (null == root) {
      throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
          "Root can"t be a null.");
    }
    this.walkerRoot = root;
    this.current = root;
    this.whatToShow = whatToShow;
    this.filter = filter;
    this.noFilter = (null == filter);
    this.entitiyReferenceExpansion = entityReferenceExpansion;
    this.defaultFilter = new WhatToShowNodeFilter(whatToShow);
  }
  private short eval(Node target) {
    short flag = defaultFilter.acceptNode(target);
    // If the node is skipped by whatToShow flag, a NodeFiilter will not be
    // called.
    if (noFilter || flag == NodeFilter.FILTER_SKIP) {
      return flag;
    }
    return filter.acceptNode(target);
  }
  private Node getVisibleNextSibling(Node target, Node root) {
    if (target == root) {
      return null;
    }
    Node tmpN = target.getNextSibling();
    if (null == tmpN) {
      Node tmpP = target.getParentNode();
      if (eval(tmpP) == NodeFilter.FILTER_SKIP) {
        return getVisibleNextSibling(tmpP, root);
      }
      return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
      return tmpN;
    case NodeFilter.FILTER_SKIP:
      Node tmpC = getVisibleFirstChild(tmpN);
      if (null != tmpC) {
        return tmpC;
      }
      // case NodeFilter.FILTER_REJECT:
    default:
      return getVisibleNextSibling(tmpN, root);
    }
  }
  private Node getVisiblePreviousSibling(Node target, Node root) {
    if (target == root) {
      return null;
    }
    Node tmpN = target.getPreviousSibling();
    if (null == tmpN) {
      Node tmpP = target.getParentNode();
      if (eval(tmpP) == NodeFilter.FILTER_SKIP) {
        return getVisiblePreviousSibling(tmpP, root);
      }
      return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
      return tmpN;
    case NodeFilter.FILTER_SKIP:
      Node tmpC = getVisibleLastChild(tmpN);
      if (null != tmpC) {
        return tmpC;
      }
      // case NodeFilter.FILTER_REJECT:
    default:
      return getVisiblePreviousSibling(tmpN, root);
    }
  }
  private Node getVisibleFirstChild(Node target) {
    if (!entitiyReferenceExpansion
        && Node.ENTITY_REFERENCE_NODE == target.getNodeType()) {
      return null;
    }
    Node tmpN = target.getFirstChild();
    if (null == tmpN) {
      return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
      return tmpN;
    case NodeFilter.FILTER_SKIP:
      Node tmpN2 = getVisibleFirstChild(tmpN);
      if (null != tmpN2) {
        return tmpN2;
      }
      // case NodeFilter.FILTER_REJECT:
    default:
      return getVisibleNextSibling(tmpN, target);
    }
  }
  private Node getVisibleLastChild(Node target) {
    if (!entitiyReferenceExpansion
        && Node.ENTITY_REFERENCE_NODE == target.getNodeType()) {
      return null;
    }
    Node tmpN = target.getLastChild();
    if (null == tmpN) {
      return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
      return tmpN;
    case NodeFilter.FILTER_SKIP:
      Node tmpN2 = getVisibleLastChild(tmpN);
      if (null != tmpN2) {
        return tmpN2;
      }
      // case NodeFilter.FILTER_REJECT:
    default:
      return getVisiblePreviousSibling(tmpN, target);
    }
  }
  private Node getVisibleParent(Node target) {
    if (target == walkerRoot) {
      return null;
    }
    Node tmpN = target.getParentNode();
    if (null == tmpN) {
      return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
      return tmpN;
      // case NodeFilter.FILTER_SKIP:
      // case NodeFilter.FILTER_REJECT:
    default:
      return getVisibleParent(tmpN);
    }
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#firstChild()
   */
  public Node firstChild() {
    Node result = getVisibleFirstChild(current);
    if (null != result) {
      current = result;
    }
    return result;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#getCurrentNode()
   */
  public Node getCurrentNode() {
    return current;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#getExpandEntityReferences()
   */
  public boolean getExpandEntityReferences() {
    return entitiyReferenceExpansion;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#getFilter()
   */
  public NodeFilter getFilter() {
    return filter;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#getRoot()
   */
  public Node getRoot() {
    return walkerRoot;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#getWhatToShow()
   */
  public int getWhatToShow() {
    return whatToShow;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#lastChild()
   */
  public Node lastChild() {
    Node result = getVisibleLastChild(current);
    if (null != result) {
      current = result;
    }
    return result;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#nextNode()
   */
  public Node nextNode() {
    // search child
    Node tmpN = getVisibleFirstChild(current);
    if (null != tmpN) {
      current = tmpN;
      return tmpN;
    }
    // search sibling
    tmpN = getVisibleNextSibling(current, walkerRoot);
    if (null != tmpN) {
      current = tmpN;
      return tmpN;
    }
    // search parent"s sibling
    Node tmpP = getVisibleParent(current);
    while (null != tmpP) {
      tmpN = getVisibleNextSibling(tmpP, walkerRoot);
      if (null != tmpN) {
        current = tmpN;
        return tmpN;
      } else {
        tmpP = getVisibleParent(tmpP);
      }
    }
    return null;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#nextSibling()
   */
  public Node nextSibling() {
    Node result = getVisibleNextSibling(current, walkerRoot);
    if (null != result) {
      current = result;
    }
    return result;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#parentNode()
   */
  public Node parentNode() {
    Node result = getVisibleParent(current);
    if (null != result) {
      current = result;
    }
    return result;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#previousNode()
   */
  public Node previousNode() {
    // search previous sibling
    Node tmpN = getVisiblePreviousSibling(current, walkerRoot);
    // no sibling, search parent
    if (null == tmpN) {
      tmpN = getVisibleParent(current);
      if (null != tmpN) {
        current = tmpN;
        return tmpN;
      }
      return null;
    }
    // search last child of previous sibling
    Node tmpC = getVisibleLastChild(tmpN);
    while (null != tmpC) {
      tmpN = tmpC;
      tmpC = getVisibleLastChild(tmpN);
    }
    if (null != tmpN) {
      current = tmpN;
      return tmpN;
    }
    return null;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#previousSibling()
   */
  public Node previousSibling() {
    Node result = getVisiblePreviousSibling(current, walkerRoot);
    if (null != result) {
      current = result;
    }
    return result;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.TreeWalker#setCurrentNode(org.w3c.dom.Node)
   */
  public void setCurrentNode(Node arg0) {
    if (arg0 == null) {
      System.out.println("Current node can"t be null.");
    }
    current = arg0;
  }
}
/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and Others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Kentarou FUKUDA - initial API and implementation
 *******************************************************************************/
 class WhatToShowNodeFilter implements NodeFilter {
  private int filter;
  public WhatToShowNodeFilter(int whatToShow) {
    this.filter = whatToShow;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.w3c.dom.traversal.NodeFilter#acceptNode(org.w3c.dom.Node)
   */
  public short acceptNode(Node arg0) {
    if (null == arg0) {
      return FILTER_REJECT;
    }
    if ((filter & (1 << (arg0.getNodeType() - 1))) != 0) {
      return FILTER_ACCEPT;
    }
    return FILTER_SKIP;
  }
}