Java/XML/DOM Node
Содержание
- 1 Accessing attributes of an element
- 2 Add another element after the first child of the root element
- 3 Add a text node before the last child of the element
- 4 Add a text node in front of the new item element
- 5 Add a text node to the beginning of the element
- 6 Add a text node to the element
- 7 Adding a CDATA Section to a DOM Document
- 8 Adding and Removing an Attribute in a DOM Element
- 9 Changing the Name of a DOM Element
- 10 Convert Hashtable to a Node
- 11 Convert NodeList To Node Array
- 12 Determining If an Attribute Was Supplied in a DOM Element
- 13 DOM Node query
- 14 DOM serializer
- 15 Extract all text children of an element
- 16 Extract the textual content from a Node.
- 17 Find Node
- 18 Find the first text descendent node of an element
- 19 Get the W3C Node instance associated with the XPath selection supplied
- 20 Get the W3C NodeList instance associated with the XPath selection supplied
- 21 Getting a DOM Element by Id
- 22 Getting and Setting an Attribute in a DOM Element
- 23 Getting a Node Relative to Another Node in a DOM Document
- 24 Getting Attributes with DOM
- 25 Getting Elements with DOM
- 26 Getting the Declared Entities in a DOM Document
- 27 Getting the Notations in a DOM Document
- 28 Getting the Root Element in a DOM Document
- 29 List an XML document with DOM parser
- 30 Listing All the Attributes of a DOM Element
- 31 Remove all attributes by first making a copy of the attribute names and then using the list to remove the attributes:
- 32 Remove All nodes
- 33 Remove this node from its parent.
- 34 Removing All the Attributes in a DOM Element
- 35 Removing a Node from a DOM Document
- 36 Returns a first child DOM Node of type ELEMENT_NODE for the specified Node
- 37 Returns a list of value for the given node
- 38 Returns a Properties object matching the given node
- 39 Returns the value of the attribute of the given element
- 40 Returns the value of the child node with the given name
- 41 Returns the value of the given node
- 42 Set or replace the text value
- 43 Simplified implementation of a Node from a Document Object Model (DOM)
- 44 Use DOM parser to deal with XML document with attributes
- 45 Verbose DOM Parser
- 46 Visiting All the Elements in a DOM Document
Accessing attributes of an element
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("sample.xml");
Element purchaseOrder = document.getDocumentElement();
Attr orderDate = purchaseOrder.getAttributeNode("date");
System.out.println(orderDate.getValue());
NamedNodeMap attrs = purchaseOrder.getAttributes();
int attrsCount = attrs.getLength();
for (int i = 0; i < attrsCount; i++) {
Attr item = (Attr) attrs.item(i);
System.out.println(""" + item.getName() + "" = "" + item.getValue() + """);
}
}
}
Add another element after the first child of the root element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
Element element2 = doc.createElement("item");
element.insertBefore(element2, element.getFirstChild().getNextSibling());
}
}
Add a text node before the last child of the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.insertBefore(doc.createTextNode("C"), element.getLastChild());
}
}
Add a text node in front of the new item element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.getParentNode().insertBefore(doc.createTextNode("B"), element);
}
}
Add a text node to the beginning of the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.insertBefore(doc.createTextNode("A"), element.getFirstChild());
}
}
Add a text node to the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.appendChild(doc.createTextNode("D"));
}
}
Adding a CDATA Section to a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
// Add a CDATA section to the root element
element = doc.getDocumentElement();
CDATASection cdata = doc.createCDATASection("data");
element.appendChild(cdata);
}
}
Adding and Removing an Attribute in a DOM Element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element.setAttribute("newAttrName", "attrValue");
element.setAttribute("newAttrName", "<>&\""");
element.removeAttribute("value");
boolean has = element.hasAttribute("value"); // true
String attrValue = element.getAttribute("value"); // mydefault
}
}
Changing the Name of a DOM Element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getDocumentElement();
Element element2 = doc.createElement("newname");
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
element2.getAttributes().setNamedItem(attr2);
}
while (element.hasChildNodes()) {
element2.appendChild(element.getFirstChild());
}
element.getParentNode().replaceChild(element2, element);
}
}
Convert Hashtable to a Node
/*
* 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: Hashtree2Node.java 475902 2006-11-16 20:03:16Z minchau $
*/
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Simple static utility to convert Hashtable to a Node.
*
* @see org.apache.xalan.xslt.EnvironmentCheck
* @see org.apache.xalan.lib.Extensions
* @author shane_curcuru@us.ibm.ru
* @version $Id: Hashtree2Node.java 475902 2006-11-16 20:03:16Z minchau $
* @xsl.usage general
*/
public abstract class Hashtree2Node
{
/**
* Convert a Hashtable into a Node tree.
*
* <p>The hash may have either Hashtables as values (in which
* case we recurse) or other values, in which case we print them
* as <item> elements, with a "key" attribute with the value
* of the key, and the element contents as the value.</p>
*
* <p>If args are null we simply return without doing anything.
* If we encounter an error, we will attempt to add an "ERROR"
* Element with exception info; if that doesn"t work we simply
* return without doing anything else byt printStackTrace().</p>
*
* @param hash to get info from (may have sub-hashtables)
* @param name to use as parent element for appended node
* futurework could have namespace and prefix as well
* @param container Node to append our report to
* @param factory Document providing createElement, etc. services
*/
public static void appendHashToNode(Hashtable hash, String name,
Node container, Document factory)
{
// Required arguments must not be null
if ((null == container) || (null == factory) || (null == hash))
{
return;
}
// name we will provide a default value for
String elemName = null;
if ((null == name) || ("".equals(name)))
elemName = "appendHashToNode";
else
elemName = name;
try
{
Element hashNode = factory.createElement(elemName);
container.appendChild(hashNode);
Enumeration keys = hash.keys();
List v = new ArrayList();
while (keys.hasMoreElements())
{
Object key = keys.nextElement();
String keyStr = key.toString();
Object item = hash.get(key);
if (item instanceof Hashtable)
{
// Ensure a pre-order traversal; add this hashes
// items before recursing to child hashes
// Save name and hash in two steps
v.add(keyStr);
v.add((Hashtable) item);
}
else
{
try
{
// Add item to node
Element node = factory.createElement("item");
node.setAttribute("key", keyStr);
node.appendChild(factory.createTextNode((String)item));
hashNode.appendChild(node);
}
catch (Exception e)
{
Element node = factory.createElement("item");
node.setAttribute("key", keyStr);
node.appendChild(factory.createTextNode("ERROR: Reading " + key + " threw: " + e.toString()));
hashNode.appendChild(node);
}
}
}
// Now go back and do the saved hashes
Iterator it = v.iterator();
while (it.hasNext())
{
// Retrieve name and hash in two steps
String n = (String) it.next();
Hashtable h = (Hashtable) it.next();
appendHashToNode(h, n, hashNode, factory);
}
}
catch (Exception e2)
{
// Ooops, just bail (suggestions for a safe thing
// to do in this case appreciated)
e2.printStackTrace();
}
}
}
Convert NodeList To Node Array
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
public static Node[] convertToArray(NodeList list)
{
int length = list.getLength();
Node[] copy = new Node[length];
for (int n = 0; n < length; ++n)
copy[n] = list.item(n);
return copy;
}
}
Determining If an Attribute Was Supplied in a DOM Element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
Attr attr = (Attr) element.getAttributeNode("attrName");
boolean wasSpecified = attr != null && attr.getSpecified();
}
}
DOM Node query
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class MainClass {
static public void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("y.xml");
NodeList configs = doc.getElementsByTagName("C");
for (int i = 0; i < configs.getLength(); i++) {
Element config = (Element) configs.item(i);
String runMode = config.getAttribute("r").trim();
if (runMode.equals("test")) {
NodeList connectionURLs = config.getElementsByTagName("URL");
System.out.println(connectionURLs.item(0).getNodeName() + "="
+ connectionURLs.item(0).getFirstChild().getNodeValue());
return;
}
}
}
}
DOM serializer
import java.io.IOException;
import java.io.Writer;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MainClass {
static private String indent = "";
public static Writer writer;
public static void serialize(Document doc) throws IOException {
serializeNode(doc, "");
writer.flush();
}
private static void serializeNode(Node node, String indentLevel) throws IOException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
Document doc = (Document) node;
writer.write("<?xml version=\"");
writer.write(doc.getXmlVersion());
writer.write("\" encoding=\"UTF-8\" standalone=\"");
if (doc.getXmlStandalone())
writer.write("yes");
else
writer.write("no");
writer.write("\"?>\n");
NodeList nodes = node.getChildNodes();
if (nodes != null)
for (int i = 0; i < nodes.getLength(); i++)
serializeNode(nodes.item(i), "");
break;
case Node.ELEMENT_NODE:
String name = node.getNodeName();
writer.write(indentLevel + "<" + name);
NamedNodeMap attributes = node.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node current = attributes.item(i);
writer.write(" " + current.getNodeName() + "=\"");
print(current.getNodeValue());
writer.write("\"");
}
writer.write(">");
NodeList children = node.getChildNodes();
if (children != null) {
if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE))
writer.write("\n");
for (int i = 0; i < children.getLength(); i++)
serializeNode(children.item(i), indentLevel + indent);
if ((children.item(0) != null)
&& (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE))
writer.write(indentLevel);
}
writer.write("</" + name + ">\n");
break;
case Node.TEXT_NODE:
print(node.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
writer.write("CDATA");
print(node.getNodeValue());
writer.write("");
break;
case Node.ruMENT_NODE:
writer.write(indentLevel + "<!-- " + node.getNodeValue() + " -->\n");
break;
case Node.PROCESSING_INSTRUCTION_NODE:
writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>\n");
break;
case Node.ENTITY_REFERENCE_NODE:
writer.write("&" + node.getNodeName() + ";");
break;
case Node.DOCUMENT_TYPE_NODE:
DocumentType docType = (DocumentType) node;
String publicId = docType.getPublicId();
String systemId = docType.getSystemId();
String internalSubset = docType.getInternalSubset();
writer.write("<!DOCTYPE " + docType.getName());
if (publicId != null)
writer.write(" PUBLIC \"" + publicId + "\" ");
else
writer.write(" SYSTEM ");
writer.write("\"" + systemId + "\"");
if (internalSubset != null)
writer.write(" [" + internalSubset + "]");
writer.write(">\n");
break;
}
}
private static void print(String s) throws IOException {
if (s == null)
return;
for (int i = 0, len = s.length(); i < len; i++) {
char c = s.charAt(i);
switch (c) {
case "<":
writer.write("<");
break;
case ">":
writer.write(">");
break;
case "&":
writer.write("&");
break;
case "\r":
writer.write("
");
break;
default:
writer.write(c);
}
}
}
}
Extract all text children of an element
/*
* Beryl - A web platform based on XML, XSLT and Java
* This file is part of the Beryl XML GUI
*
* Copyright (C) 2004 Wenzel Jakob <wazlaf@tigris.org>
*
* This program is free software; you can redistribute it and/or
* modify it 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.
* This program 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 program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-3107 USA
*/
import java.io.StringWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Miscellaneous XML utility functions
*/
public class XMLUtils {
/**
* Extract all text children of an element
*/
public static String extractTextChildren(Element parentNode) {
NodeList childNodes = parentNode.getChildNodes();
String result = new String();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.TEXT_NODE) {
result += node.getNodeValue();
}
}
return result;
}
}
Extract the textual content from a Node.
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Various utilities to make up for the fact that DOM isn"t as useful as it
* could be.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class DomUtil
{
/**
* Extract the textual content from a Node.
* This is rather like the XPath value of a Node.
* @param node The node to extract the text from
* @return The textual value of the node
*/
public static String getText(Node node)
{
StringBuffer reply = new StringBuffer();
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
if ((child instanceof CharacterData && !(child instanceof Comment)) || child instanceof EntityReference)
{
reply.append(child.getNodeValue());
}
else if (child.getNodeType() == Node.ELEMENT_NODE)
{
reply.append(getText(child));
}
}
return reply.toString();
}
}
Find Node
/*
* 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;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author Abey Mullassery
*
*/
public class Main {
public static Node findNode(
Node root,
String elementName,
boolean deep,
boolean elementsOnly) {
//Check to see if root has any children if not return null
if (!(root.hasChildNodes()))
return null;
//Root has children, so continue searching for them
Node matchingNode = null;
String nodeName = null;
Node child = null;
NodeList childNodes = root.getChildNodes();
int noChildren = childNodes.getLength();
for (int i = 0; i < noChildren; i++) {
if (matchingNode == null) {
child = childNodes.item(i);
nodeName = child.getNodeName();
if ((nodeName != null) & (nodeName.equals(elementName)))
return child;
if (deep)
matchingNode =
findNode(child, elementName, deep, elementsOnly);
} else
break;
}
if (!elementsOnly) {
NamedNodeMap childAttrs = root.getAttributes();
noChildren = childAttrs.getLength();
for (int i = 0; i < noChildren; i++) {
if (matchingNode == null) {
child = childAttrs.item(i);
nodeName = child.getNodeName();
if ((nodeName != null) & (nodeName.equals(elementName)))
return child;
} else
break;
}
}
return matchingNode;
}
}
Find the first text descendent node of an element
/*
* Copyright (C) 2001 Christian Cryder [christianc@granitepeaks.ru]
*
* This library is free software; you can redistribute it and/or
* modify it 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.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: DOMUtil.java 114 2005-12-09 15:51:51Z christianc $
*/
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* DOM related utility functions.
*/
public class DOMUtil {
private static byte[] sep = System.getProperty("line.separator").getBytes();
/**
* Find the first text descendent node of an element.
* This recursively looks more than one level to search
* for text in font nodes, etc.
*
* @param node The starting node for the search.
* @return The text node or null if not found.
*/
public static Text findFirstText(Node node) {
if (node instanceof Text) return (Text) node;
for (Node child = node.getFirstChild(); child!=null; child = child.getNextSibling()) {
Text text = findFirstText(child);
if (text!=null) return text;
}
return null;
}
/**
* Gets the first text descendent node of an element.
* This recursively looks more than one level to search
* for text in font nodes, etc. Throws a DOMException
* if the Text object is not found.
*
* @param node The starting node for the search.
* @return The text node or null if not found.
* @throws DOMException if the Text object is not found
*/
public static Text getFirstText(Node node) {
Text text = findFirstText(node);
if (text==null) {
String msg = "No child text mode found for element";
String id = getID(node);
throw new DOMException((short) -1, msg+(id!=null ? "; id=\""+id+"\"" : ""));
}
return text;
}
/**
* Automatically set text in a Node. Basically we find the first
* Text node beneath the current node and replace it with a
* CDATASection for the incoming text. All other Text nodes are
* removed. Throws a DOMException if it"s illegal to add a Text
* child to the particular node.
*
* @param node the starting node for the search.
* @param text the text to be set
* @param allowMarkupInText whether to allow markup in text to pass through unparsed
* @return the updated node
* @throws DOMException if the Text object is not found
*/
public static Node setTextInNode(Node node, String text, boolean allowMarkupInText) {
//start by setting the value in the first text node we find with a comment
Comment comment = node.getOwnerDocument().createComment("");
Node newNode = null;
//csc_092701.1 - support both encoded/unencoded text
if (allowMarkupInText) newNode = node.getOwnerDocument().createCDATASection(text);
else newNode = node.getOwnerDocument().createTextNode(text);
//System.out.println ("newNode: "+newNode);
Text textComp = DOMUtil.findFirstText((Element) node);
//System.out.println ("textComp:"+textComp);
if (textComp==null) {
node.appendChild(comment);
} else {
Node parent = textComp.getParentNode();
parent.replaceChild(comment, textComp);
}
//now remove all the rest of the text nodes
removeAllTextNodes(node);
//now replace the comment with the newNode
Node parent = comment.getParentNode();
parent.replaceChild(newNode, comment);
//System.out.println ("parent: "+parent);
//System.out.println ("result: "+DOMUtil.findFirstText((Element) parent));
//DOMUtil.printStackTrace(parent.getOwnerDocument().getDocumentElement());
return node;
}
/**
* Remove all text nodes below this node
*
* @param node The starting node for the search.
*/
public static void removeAllTextNodes(Node node) {
if (node==null) return;
if (!node.hasChildNodes()) return;
NodeList nl = node.getChildNodes();
for (int i=nl.getLength()-1; i>=0; i--) {
Node n = (Node) nl.item(i);
if (n instanceof Text) node.removeChild(n);
else removeAllTextNodes(n);
}
}
/**
* Given a Node name, return the "id" attribute if it exists.
* If it does not exist, return null instead. This is basically
* just a convenience method to cast the node to element and
* return the id from that.
*
* @param node the node name in question
* @return the id value for the given node, if it exists. null if
* doesn"t
*/
public static String getID(Node node) {
return getID(node, null);
}
/**
* Given a Node, return the "id" attribute if it exists.
* If it does not exist, return nullResponse instead. This is basically
* just a convenience method to cast the node to element and
* return the id from that.
*
* @param node the node in question
* @param nullResponse the response to be returned if the id attribute
* does not exist
* @return the id value for the given node, if it exists. null if
* doesn"t
*/
public static String getID(Node node, String nullResponse) {
String nodeName = nullResponse;
if (node instanceof Element) {
nodeName = ((Element) node).getAttribute("id");
}
return nodeName;
}
protected static void print(OutputStream out, String s) {
if (out!=null) try {
out.write(s.getBytes());
out.write(sep);
} catch (IOException ioe) {}
}
}
Get the W3C Node instance associated with the XPath selection supplied
/*
Milyn - Copyright (C) 2006
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software
Foundation.
This library 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:
http://www.gnu.org/licenses/lgpl.txt
*/
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/**
* XMl utility methods.
*
* @author Tom Fennelly
*/
public class XmlUtil {
/**
* Document validation types.
*/
public static enum VALIDATION_TYPE {
/**
* No validation.
*/
NONE,
/**
* DTD based validation.
*/
DTD,
/**
* XSD based validation.
*/
XSD,
}
private static String ELEMENT_NAME_FUNC = "/name()";
private static XPathFactory xPathFactory = XPathFactory.newInstance();
/**
* Get the W3C Node instance associated with the XPath selection supplied.
*
* @param node The document node to be searched.
* @param xpath The XPath String to be used in the selection.
* @return The W3C Node instance at the specified location in the document,
* or null.
*/
public static Node getNode(Node node, String xpath) {
NodeList nodeList = getNodeList(node, xpath);
if (nodeList == null || nodeList.getLength() == 0) {
return null;
} else {
return nodeList.item(0);
}
}
/**
* Get the W3C NodeList instance associated with the XPath selection
* supplied.
*
* @param node The document node to be searched.
* @param xpath The XPath String to be used in the selection.
* @return The W3C NodeList instance at the specified location in the
* document, or null.
*/
public static NodeList getNodeList(Node node, String xpath) {
if (node == null) {
throw new IllegalArgumentException(
"null "document" arg in method call.");
} else if (xpath == null) {
throw new IllegalArgumentException(
"null "xpath" arg in method call.");
}
try {
XPath xpathEvaluater = xPathFactory.newXPath();
if (xpath.endsWith(ELEMENT_NAME_FUNC)) {
return (NodeList) xpathEvaluater.evaluate(xpath.substring(0,
xpath.length() - ELEMENT_NAME_FUNC.length()), node,
XPathConstants.NODESET);
} else {
return (NodeList) xpathEvaluater.evaluate(xpath, node,
XPathConstants.NODESET);
}
} catch (XPathExpressionException e) {
throw new IllegalArgumentException("bad "xpath" expression ["
+ xpath + "].");
}
}
}
Get the W3C NodeList instance associated with the XPath selection supplied
/*
Milyn - Copyright (C) 2006
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software
Foundation.
This library 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:
http://www.gnu.org/licenses/lgpl.txt
*/
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/**
* XMl utility methods.
*
* @author Tom Fennelly
*/
public class XmlUtil {
/**
* Document validation types.
*/
public static enum VALIDATION_TYPE {
/**
* No validation.
*/
NONE,
/**
* DTD based validation.
*/
DTD,
/**
* XSD based validation.
*/
XSD,
}
private static String ELEMENT_NAME_FUNC = "/name()";
private static XPathFactory xPathFactory = XPathFactory.newInstance();
/**
* Get the W3C NodeList instance associated with the XPath selection
* supplied.
*
* @param node The document node to be searched.
* @param xpath The XPath String to be used in the selection.
* @return The W3C NodeList instance at the specified location in the
* document, or null.
*/
public static NodeList getNodeList(Node node, String xpath) {
if (node == null) {
throw new IllegalArgumentException(
"null "document" arg in method call.");
} else if (xpath == null) {
throw new IllegalArgumentException(
"null "xpath" arg in method call.");
}
try {
XPath xpathEvaluater = xPathFactory.newXPath();
if (xpath.endsWith(ELEMENT_NAME_FUNC)) {
return (NodeList) xpathEvaluater.evaluate(xpath.substring(0,
xpath.length() - ELEMENT_NAME_FUNC.length()), node,
XPathConstants.NODESET);
} else {
return (NodeList) xpathEvaluater.evaluate(xpath, node,
XPathConstants.NODESET);
}
} catch (XPathExpressionException e) {
throw new IllegalArgumentException("bad "xpath" expression ["
+ xpath + "].");
}
}
}
Getting a DOM Element by Id
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
String attrValue = element.getAttribute("value");
}
}
Getting and Setting an Attribute in a DOM Element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
boolean has = element.hasAttribute("value");
String attrValue = element.getAttribute("value");
element.setAttribute("value", "newValue1");
element = doc.getElementById("key2");
has = element.hasAttribute("value");
attrValue = element.getAttribute("value");
element.setAttribute("value", "a<\""&>z");
}
}
Getting a Node Relative to Another Node in a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc1 = factory.newDocumentBuilder().parse(new File("filename"));
NodeList list = doc1.getElementsByTagName("entry");
Element element = (Element) list.item(0);
Document doc2 = factory.newDocumentBuilder().parse(new File("infilename2.xml"));
// Make a copy of the element subtree suitable for inserting into doc2
Node node = doc2.importNode(element, true);
// Get the parent
Node parent = node.getParentNode();
// Get children
NodeList children = node.getChildNodes();
// Get first child; null if no children
Node child = node.getFirstChild();
// Get last child; null if no children
child = node.getLastChild();
// Get next sibling; null if node is last child
Node sibling = node.getNextSibling();
// Get previous sibling; null if node is first child
sibling = node.getPreviousSibling();
// Get first sibling
sibling = node.getParentNode().getFirstChild();
// Get last sibling
sibling = node.getParentNode().getLastChild();
}
}
Getting Attributes with DOM
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
public class MainClass {
public static void main(String args[]) throws IOException, SAXException {
DOMParser parser = new DOMParser();
parser.parse("games.xml");
Document dom = parser.getDocument();
NodeList games = dom.getElementsByTagName("game");
for (int i = 0; i < games.getLength(); i++) {
Node aNode = games.item(i);
System.out.println(aNode.getFirstChild().getNodeValue());
NamedNodeMap attributes = aNode.getAttributes();
for (int a = 0; a < attributes.getLength(); a++) {
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
}
Getting Elements with DOM
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.SAXException;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class MainClass {
public static void main(String args[]) throws IOException, SAXException {
DOMParser parser = new DOMParser();
parser.parse("games.xml");
Document dom = parser.getDocument();
NodeList games = dom.getElementsByTagName("game");
for (int i = 0; i < games.getLength(); i++) {
Node aNode = games.item(i);
System.out.println(textNode.getFirstChild().getNodeValue());
}
}
}
Getting the Declared Entities in a DOM Document
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Entity;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Map entityValues = new HashMap();
getEntityValues(doc, entityValues);
NamedNodeMap entities = doc.getDoctype().getEntities();
for (int i = 0; i < entities.getLength(); i++) {
Entity entity = (Entity) entities.item(i);
System.out.println(entity);
String entityName = entity.getNodeName();
System.out.println(entityName);
String entityPublicId = entity.getPublicId();
System.out.println(entityPublicId);
String entitySystemId = entity.getSystemId();
System.out.println(entitySystemId);
Node entityValue = (Node) entityValues.get(entityName);
System.out.println(entityValue);
}
}
public static void getEntityValues(Node node, Map map) {
if (node instanceof EntityReference) {
map.put(node.getNodeName(), node);
}
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
getEntityValues(list.item(i), map);
}
}
}
Getting the Notations in a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Notation;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
NamedNodeMap notations = doc.getDoctype().getNotations();
for (int i = 0; i < notations.getLength(); i++) {
Notation notation = (Notation) notations.item(i);
String notationName = notation.getNodeName();
String notationPublicId = notation.getPublicId();
String notationSystemId = notation.getSystemId();
}
}
}
Getting the Root Element in a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element root = null;
NodeList list = doc.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
if (list.item(i) instanceof Element) {
root = (Element) list.item(i);
break;
}
}
root = doc.getDocumentElement();
}
}
List an XML document with DOM parser
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class MainClass implements ErrorHandler {
public static void main(String args[]) throws Exception {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setValidating(true);
DocumentBuilder builder = null;
builder = builderFactory.newDocumentBuilder();
builder.setErrorHandler(new MainClass());
Document xmlDoc = null;
xmlDoc = builder.parse(new File("y.xml"));
DocumentType doctype = xmlDoc.getDoctype();
System.out.println("DOCTYPE node:\n" + doctype);
listNodes(xmlDoc.getDocumentElement(), "");
}
static void listNodes(Node node, String indent) {
String nodeName = node.getNodeName();
System.out.println(indent + nodeName + " Node, type is "
+ node.getClass().getName() + ":");
System.out.println(indent + " " + node);
NodeList list = node.getChildNodes();
if (list.getLength() > 0) {
System.out.println(indent + "Child Nodes of " + nodeName + " are:");
for (int i = 0; i < list.getLength(); i++)
listNodes(list.item(i), indent + " ");
}
}
public void fatalError(SAXParseException spe) throws SAXException {
System.out.println("Fatal error at line " + spe.getLineNumber());
System.out.println(spe.getMessage());
throw spe;
}
public void warning(SAXParseException spe) {
System.out.println("Warning at line " + spe.getLineNumber());
System.out.println(spe.getMessage());
}
public void error(SAXParseException spe) {
System.out.println("Error at line " + spe.getLineNumber());
System.out.println(spe.getMessage());
}
}
<?xml version="1.0"?>
<!DOCTYPE address SYSTEM "AddressDoc.dtd">
<address>
<buildingnumber> 29 </buildingnumber>
<street> South Lasalle Street</street>
<city>Chicago</city>
<state>Illinois</state>
<zip>60603</zip>
</address>
<!ELEMENT address (buildingnumber, street, city, state, zip)>
<!ELEMENT buildingnumber (#PCDATA)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
Listing All the Attributes of a DOM Element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
NamedNodeMap attrs = element.getAttributes();
int numAttrs = attrs.getLength();
for (int i = 0; i < numAttrs; i++) {
Attr attr = (Attr) attrs.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
}
}
}
Remove all attributes by first making a copy of the attribute names and then using the list to remove the attributes:
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
NamedNodeMap attrs = element.getAttributes();
String[] names = new String[attrs.getLength()];
for (int i = 0; i < names.length; i++) {
names[i] = attrs.item(i).getNodeName();
}
for (int i = 0; i < names.length; i++) {
attrs.removeNamedItem(names[i]);
}
}
}
Remove All nodes
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
removeAll(doc, Node.ELEMENT_NODE, "junk");
removeAll(doc, Node.ruMENT_NODE, null);
doc.normalize();
}
public static void removeAll(Node node, short nodeType, String name) {
if (node.getNodeType() == nodeType && (name == null || node.getNodeName().equals(name))) {
node.getParentNode().removeChild(node);
} else {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
removeAll(list.item(i), nodeType, name);
}
}
}
}
Remove this node from its parent.
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
import org.w3c.dom.Node;
public class Utils {
/**
* Remove this node from its parent.
* @param node the node to remove
* @return Node removed
*/
public Node removeNode(Node node) {
return node.getParentNode().removeChild(node);
}
}
Removing All the Attributes in a DOM Element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
NamedNodeMap attrs = element.getAttributes();
while (attrs.getLength() > 0) {
attrs.removeNamedItem(attrs.item(0).getNodeName());
}
}
}
Removing a Node from a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = (Element) doc.getElementsByTagName("junk").item(0);
element.getParentNode().removeChild(element);
}
}
Returns a first child DOM Node of type ELEMENT_NODE for the specified Node
/**
* 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 org.w3c.dom.Node;
public final class NodeUtils {
/**
* Returns a first child DOM Node of type ELEMENT_NODE
* for the specified Node.
*/
public static Node getChildElementNode(Node xmlNode) {
if (xmlNode == null || !xmlNode.hasChildNodes()) {
return null;
}
xmlNode = xmlNode.getFirstChild();
while (xmlNode != null
&& xmlNode.getNodeType() != Node.ELEMENT_NODE) {
xmlNode = xmlNode.getNextSibling();
}
return xmlNode;
}
}
Returns a list of value for the given node
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it 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 any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Returns a list of value for the given node.
* @param ns the namespace.
* @param base the element from where to search.
* @param name of the element to get.
* @return the list of value of this element.
*/
public static List<String> getStringListValueElement(final String ns, final Element base, final String name) {
List<String> returnedlist = new ArrayList<String>();
// Get element
NodeList list = base.getElementsByTagNameNS(ns, name);
int length = list.getLength();
// Get all values of all elements
if (length > 0) {
for (int i = 0; i < length; i++) {
Element element = (Element) list.item(i);
Node node = element.getFirstChild();
if (node != null) {
returnedlist.add(node.getNodeValue());
}
}
}
return returnedlist;
}
}
Returns a Properties object matching the given node
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it 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 any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Returns a Properties object matching the given node.
* @param ns the namespace.
* @param base the element from where to search.
* @param name of the element to get.
* @return the value of this element.
*/
public static Properties getPropertiesValueElement(final String ns, final Element base, final String name) {
Properties returnedProperties = new Properties();
// Get element
NodeList list = base.getElementsByTagNameNS(ns, name);
if (list.getLength() == 1) {
Element element = (Element) list.item(0);
// Get property element
NodeList properties = element.getElementsByTagNameNS(ns, "property");
// If properties is present, analyze them and add them
if (properties.getLength() > 0) {
for (int i = 0; i < properties.getLength(); i++) {
Element elemProperty = (Element) properties.item(i);
String pName = getAttributeValue(elemProperty, "name");
String pValue = getAttributeValue(elemProperty, "value");
if (pName != null && pValue != null) {
returnedProperties.setProperty(pName, pValue);
}
}
}
} else if (list.getLength() > 1) {
throw new IllegalStateException("Element "" + name + "" on "" + base + "" should be unique but there are ""
+ list.getLength() + "" elements");
}
return returnedProperties;
}
/**
* Returns the value of the attribute of the given element.
* @param base the element from where to search.
* @param name of the attribute to get.
* @return the value of this element.
*/
public static String getAttributeValue(final Element base, final String name) {
// get attribute of this element...
NamedNodeMap mapAttributes = base.getAttributes();
Node node = mapAttributes.getNamedItem(name);
if (node != null) {
return node.getNodeValue();
}
return null;
}
}
Returns the value of the attribute of the given element
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it 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 any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Utility class, no constructor.
*/
private XMLUtils() {
}
/**
* Returns the value of the attribute of the given element.
* @param base the element from where to search.
* @param name of the attribute to get.
* @return the value of this element.
*/
public static String getAttributeValue(final Element base, final String name) {
// get attribute of this element...
NamedNodeMap mapAttributes = base.getAttributes();
Node node = mapAttributes.getNamedItem(name);
if (node != null) {
return node.getNodeValue();
}
return null;
}
}
Returns the value of the child node with the given name
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it 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 any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Returns the value of the child node with the given name.
* @param base the element from where to search.
* @param name of the element to get.
* @return the value of this element.
*/
public static String getChildStringValueForElement(final Element base, final String name) {
String value = null;
NodeList nodeList = base.getChildNodes();
if (nodeList.getLength() > 0) {
int length = nodeList.getLength();
for (int i = 0; i < length; i++) {
Node node = nodeList.item(i);
// Get an element, create an instance of the element
if (Node.ELEMENT_NODE == node.getNodeType()) {
if (name.equals(node.getNodeName())) {
// Get value of this child
Node elNode = ((Element) node).getFirstChild();
if (elNode != null) {
value = elNode.getNodeValue();
break;
}
}
}
}
}
return value;
}
}
Returns the value of the given node
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it 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 any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Returns the value of the given node.
* @param base the element from where to search.
* @param name of the element to get.
* @return the value of this element.
*/
public static String getStringValueElement(final Element base, final String name) {
String value = null;
// Get element
NodeList list = base.getElementsByTagName(name);
if (list.getLength() == 1) {
Element element = (Element) list.item(0);
Node node = element.getFirstChild();
if (node != null) {
value = node.getNodeValue();
}
} else if (list.getLength() > 1) {
throw new IllegalStateException("Element "" + name + "" on "" + base + "" should be unique but there are ""
+ list.getLength() + "" elements");
}
if (value != null) {
value = value.trim();
}
return value;
}
}
Set or replace the text value
import org.w3c.dom.Node;
/**
*
*
* @author Costin Manolache
*/
public class Main {
/** Set or replace the text value
*/
public static void setText(Node node, String val) {
Node chld=DomUtil.getChild(node, Node.TEXT_NODE);
if( chld == null ) {
Node textN=node.getOwnerDocument().createTextNode(val);
node.appendChild(textN);
return;
}
// change the value
chld.setNodeValue(val);
}
}
Simplified implementation of a Node from a Document Object Model (DOM)
/*
* 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.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
/**
* Simplified implementation of a Node from a Document Object Model (DOM)
* parse of an XML document. This class is used to represent a DOM tree
* so that the XML parser"s implementation of <code>org.w3c.dom</code> need
* not be visible to the remainder of Jasper.
* <p>
* <strong>WARNING</strong> - Construction of a new tree, or modifications
* to an existing one, are not thread-safe and such accesses must be
* synchronized.
*
* @author Craig R. McClanahan
* @version $Revision: 515 $ $Date: 2008-03-17 22:02:23 +0100 (Mon, 17 Mar 2008) $
*/
public class TreeNode {
// ----------------------------------------------------------- Constructors
/**
* Construct a new node with no parent.
*
* @param name The name of this node
*/
public TreeNode(String name) {
this(name, null);
}
/**
* Construct a new node with the specified parent.
*
* @param name The name of this node
* @param parent The node that is the parent of this node
*/
public TreeNode(String name, TreeNode parent) {
super();
this.name = name;
this.parent = parent;
if (this.parent != null)
this.parent.addChild(this);
}
// ----------------------------------------------------- Instance Variables
/**
* The attributes of this node, keyed by attribute name,
* Instantiated only if required.
*/
protected HashMap attributes = null;
/**
* The body text associated with this node (if any).
*/
protected String body = null;
/**
* The children of this node, instantiated only if required.
*/
protected ArrayList children = null;
/**
* The name of this node.
*/
protected String name = null;
/**
* The parent node of this node.
*/
protected TreeNode parent = null;
// --------------------------------------------------------- Public Methods
/**
* Add an attribute to this node, replacing any existing attribute
* with the same name.
*
* @param name The attribute name to add
* @param value The new attribute value
*/
public void addAttribute(String name, String value) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, value);
}
/**
* Add a new child node to this node.
*
* @param node The new child node
*/
public void addChild(TreeNode node) {
if (children == null)
children = new ArrayList();
children.add(node);
}
/**
* Return the value of the specified node attribute if it exists, or
* <code>null</code> otherwise.
*
* @param name Name of the requested attribute
*/
public String findAttribute(String name) {
if (attributes == null)
return (null);
else
return ((String) attributes.get(name));
}
/**
* Return an Iterator of the attribute names of this node. If there are
* no attributes, an empty Iterator is returned.
*/
public Iterator findAttributes() {
if (attributes == null)
return (Collections.EMPTY_LIST.iterator());
else
return (attributes.keySet().iterator());
}
/**
* Return the first child node of this node with the specified name,
* if there is one; otherwise, return <code>null</code>.
*
* @param name Name of the desired child element
*/
public TreeNode findChild(String name) {
if (children == null)
return (null);
Iterator items = children.iterator();
while (items.hasNext()) {
TreeNode item = (TreeNode) items.next();
if (name.equals(item.getName()))
return (item);
}
return (null);
}
/**
* Return an Iterator of all children of this node. If there are no
* children, an empty Iterator is returned.
*/
public Iterator findChildren() {
if (children == null)
return (Collections.EMPTY_LIST.iterator());
else
return (children.iterator());
}
/**
* Return an Iterator over all children of this node that have the
* specified name. If there are no such children, an empty Iterator
* is returned.
*
* @param name Name used to select children
*/
public Iterator findChildren(String name) {
if (children == null)
return (Collections.EMPTY_LIST.iterator());
ArrayList results = new ArrayList();
Iterator items = children.iterator();
while (items.hasNext()) {
TreeNode item = (TreeNode) items.next();
if (name.equals(item.getName()))
results.add(item);
}
return (results.iterator());
}
/**
* Return the body text associated with this node (if any).
*/
public String getBody() {
return (this.body);
}
/**
* Return the name of this node.
*/
public String getName() {
return (this.name);
}
/**
* Remove any existing value for the specified attribute name.
*
* @param name The attribute name to remove
*/
public void removeAttribute(String name) {
if (attributes != null)
attributes.remove(name);
}
/**
* Remove a child node from this node, if it is one.
*
* @param node The child node to remove
*/
public void removeNode(TreeNode node) {
if (children != null)
children.remove(node);
}
/**
* Set the body text associated with this node (if any).
*
* @param body The body text (if any)
*/
public void setBody(String body) {
this.body = body;
}
/**
* Return a String representation of this TreeNode.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
toString(sb, 0, this);
return (sb.toString());
}
// ------------------------------------------------------ Protected Methods
/**
* Append to the specified StringBuffer a character representation of
* this node, with the specified amount of indentation.
*
* @param sb The StringBuffer to append to
* @param indent Number of characters of indentation
* @param node The TreeNode to be printed
*/
protected void toString(StringBuffer sb, int indent,
TreeNode node) {
int indent2 = indent + 2;
// Reconstruct an opening node
for (int i = 0; i < indent; i++)
sb.append(" ");
sb.append("<");
sb.append(node.getName());
Iterator names = node.findAttributes();
while (names.hasNext()) {
sb.append(" ");
String name = (String) names.next();
sb.append(name);
sb.append("=\"");
String value = node.findAttribute(name);
sb.append(value);
sb.append("\"");
}
sb.append(">\n");
// Reconstruct the body text of this node (if any)
String body = node.getBody();
if ((body != null) && (body.length() > 0)) {
for (int i = 0; i < indent2; i++)
sb.append(" ");
sb.append(body);
sb.append("\n");
}
// Reconstruct child nodes with extra indentation
Iterator children = node.findChildren();
while (children.hasNext()) {
TreeNode child = (TreeNode) children.next();
toString(sb, indent2, child);
}
// Reconstruct a closing node marker
for (int i = 0; i < indent; i++)
sb.append(" ");
sb.append("</");
sb.append(node.getName());
sb.append(">\n");
}
}
Use DOM parser to deal with XML document with attributes
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
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.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class MainClass implements ErrorHandler {
public static void main(String args[]) throws Exception {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setValidating(true);
builderFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = null;
builder = builderFactory.newDocumentBuilder();
builder.setErrorHandler(new MainClass());
Document xmlDoc = builder.parse(new File("y.xml"));
DocumentType doctype = xmlDoc.getDoctype();
System.out.println("DOCTYPE node:\n" + doctype);
listNodes(xmlDoc.getDocumentElement(), "");
}
static void listNodes(Node node, String indent) {
String nodeName = node.getNodeName();
System.out.println(indent + nodeName + " Node, type is " + node.getClass().getName() + ":");
System.out.println(indent + " " + node);
if (node instanceof Element && node.hasAttributes()) {
System.out.println(indent + "Element Attributes are:");
NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attribute = (Attr) attrs.item(i);
System.out.println(indent + attribute.getName() + "="
+ attribute.getValue());
}
}
NodeList list = node.getChildNodes();
if (list.getLength() > 0) {
System.out.println(indent + "Child Nodes of " + nodeName + " are:");
for (int i = 0; i < list.getLength(); i++)
listNodes(list.item(i), indent + " ");
}
}
public void fatalError(SAXParseException spe) throws SAXException {
System.out.println("Fatal error at line " + spe.getLineNumber());
System.out.println(spe.getMessage());
throw spe;
}
public void warning(SAXParseException spe) {
System.out.println("Warning at line " + spe.getLineNumber());
System.out.println(spe.getMessage());
}
public void error(SAXParseException spe) {
System.out.println("Error at line " + spe.getLineNumber());
System.out.println(spe.getMessage());
}
}
<?xml version="1.0"?>
<!DOCTYPE circle
[
<!ELEMENT circle (position)>
<!ATTLIST circle
radius CDATA #REQUIRED
>
<!ELEMENT position EMPTY>
<!ATTLIST position
x CDATA #REQUIRED
y CDATA #REQUIRED
>
]>
<circle radius="15">
<position x="30" y="50"/>
</circle>
Verbose DOM Parser
import java.io.FileInputStream;
import java.util.Arrays;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MainClass {
public static void main(String[] args) throws Exception {
boolean namespace = true;
boolean validating = true;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(namespace);
dbf.setValidating(validating);
DocumentBuilder parser = dbf.newDocumentBuilder();
FileInputStream fis = new FileInputStream("y.xml");
Document doc = parser.parse(fis, "y.xml");
passNode(doc, 0);
}
private static void passNode(Node n, int i) {
println(n.getNodeName() + " [" + nodeTypeToString(n.getNodeType()) + "]", i);
printNameValue("Local Name", n.getLocalName(), i + 2);
printNameValue("Namespace URI", n.getNamespaceURI(), i + 2);
printNameValue("Prefix", n.getPrefix(), i + 2);
printNameValue("Value", n.getNodeValue(), i + 2);
if (n.hasAttributes()) {
nodeMapWalk("Attributes", n.getAttributes(), i + 2);
}
if (n.hasChildNodes()) {
nodeListWalk("Children", n.getChildNodes(), i + 2);
}
}
private static void println(String s, int i) {
indent(i);
System.out.println(s);
}
private static void indent(int i) {
char[] indent = new char[i];
Arrays.fill(indent, " ");
System.out.print(indent);
}
private static void printNameValue(String name, String value, int i) {
if (value != null) {
println(name + ":" + value, i);
}
}
private static void nodeListWalk(String name, NodeList nl, int i) {
println(name + ":", i);
int count = nl.getLength();
for (int a = 0; a < count; a++) {
passNode(nl.item(a), i + 2);
}
}
private static void nodeMapWalk(String name, NamedNodeMap nnm, int i) {
println(name + ":", i);
int count = nnm.getLength();
for (int a = 0; a < count; a++) {
passNode(nnm.item(a), i + 2);
}
}
private static String nodeTypeToString(short n) {
String nodeType = null;
switch (n) {
case Node.ATTRIBUTE_NODE:
nodeType = "Attribute";
break;
case Node.CDATA_SECTION_NODE:
nodeType = "CDATA Section";
break;
case Node.ruMENT_NODE:
nodeType = "Comment";
break;
case Node.DOCUMENT_FRAGMENT_NODE:
nodeType = "Document Fragment";
break;
case Node.DOCUMENT_NODE:
nodeType = "Document";
break;
case Node.DOCUMENT_TYPE_NODE:
nodeType = "Document Type";
break;
case Node.ELEMENT_NODE:
nodeType = "Element";
break;
case Node.ENTITY_NODE:
nodeType = "Entity";
break;
case Node.ENTITY_REFERENCE_NODE:
nodeType = "Entity.Reference";
break;
case Node.NOTATION_NODE:
nodeType = "Notation";
break;
case Node.PROCESSING_INSTRUCTION_NODE:
nodeType = "Processing Instruction";
break;
case Node.TEXT_NODE:
nodeType = "Text";
break;
}
return nodeType;
}
}
Visiting All the Elements in a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
NodeList list = doc.getElementsByTagName("*");
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element) list.item(i);
}
}
}