Java Tutorial/XML/DOM Edit

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

Adding a New Entry to the End of a List

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      append(doc, "newName", "1111111111", "newEmail");
      
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void append(Document doc, String name, String phone, String email) {
    Element personNode = doc.createElement("person");
    Element nameNode = doc.createElement("name");
    personNode.appendChild(nameNode);
    Text nametextNode = doc.createTextNode(name);
    nameNode.appendChild(nametextNode);
    Element phoneNode = doc.createElement("phone");
    personNode.appendChild(phoneNode);
    Text phonetextNode = doc.createTextNode(phone);
    phoneNode.appendChild(phonetextNode);
    Element emailNode = doc.createElement("email");
    personNode.appendChild(emailNode);
    Text emailtextNode = doc.createTextNode(email);
    emailNode.appendChild(emailtextNode);
    Element root = doc.getDocumentElement();
    root.appendChild(personNode);
  }
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person>
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
    <person>
        <name>
            newName
        </name>
        <phone>
            1111111111
        </phone>
        <email>
            newEmail
        </email>
    </person>
</folks>


A Method for Inserting a New Entry in a List

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      insert(doc, "newName", "1111111111", "newEmail");
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void insert(Document doc, String name, String phone, String email) {
    Element personNode = doc.createElement("person");
    Element nameNode = doc.createElement("name");
    personNode.appendChild(nameNode);
    Text nametextNode = doc.createTextNode(name);
    nameNode.appendChild(nametextNode);
    Element phoneNode = doc.createElement("phone");
    personNode.appendChild(phoneNode);
    Text phonetextNode = doc.createTextNode(phone);
    phoneNode.appendChild(phonetextNode);
    Element emailNode = doc.createElement("email");
    personNode.appendChild(emailNode);
    Text emailtextNode = doc.createTextNode(email);
    emailNode.appendChild(emailtextNode);
    Element root = doc.getDocumentElement();
    Node firstChildNode = root.getFirstChild();
    root.insertBefore(personNode, firstChildNode);
  }
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}



<?xml version="1.0" standalone="yes"?>
<folks>
    <person>
        <name>
            newName
        </name>
        <phone>
            1111111111
        </phone>
        <email>
            newEmail
        </email>
    </person>
    <person>
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


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);
  }
}





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 New Container

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * 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 Element createNewContainer(Document document, Element parent,
      String childElement) {
    Element child = (Element) document.createElement(childElement);
    parent.appendChild(child);
    return child;
  }
}





Creating an XML Document from a DOM Tree

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMCopy {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person>
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


Deleting an Attribute

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      delAttribute(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void delAttribute(Document doc) {
    Element root = doc.getDocumentElement();
    Element person = (Element)root.getFirstChild();
    person.removeAttribute("number");
    person.removeAttribute("dept");
  }

  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ATTLIST person number CDATA #IMPLIED
                 dept CDATA "staff">
]>
<folks>
    <person number="3412" dept="medical">
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person dept="staff">
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


Deleting a Tree Node

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      deleteFirstElement(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void deleteFirstElement(Document doc) {
    Element root = doc.getDocumentElement();
    Element child = (Element)root.getFirstChild();
    root.removeChild(child);
  }

  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>





Duplicating a Portion of the Tree

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      duplicatePerson(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void duplicatePerson(Document doc) {
    Element root = doc.getDocumentElement();
    Element origPerson = (Element)root.getFirstChild();
    Element newPerson = (Element)origPerson.cloneNode(true);
    root.appendChild(newPerson);
  }

  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person>
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
    <person>
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


Editing by Using a Document Fragment: Creating a DocumentFragment Subtree and Appending to the Document

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      addFragment(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void addFragment(Document doc) {
    Element person;
    Element root = doc.getDocumentElement();
    DocumentFragment fragment = doc.createDocumentFragment();
    person = makePersonNode(doc,"Name 1","555-4444");
    fragment.appendChild(person);
    person = makePersonNode(doc,"Name 2","555-9999");
    fragment.appendChild(person);
    root.appendChild(fragment);
  }
  private static Element makePersonNode(Document doc,String name,String phone) {
    Element nameNode = doc.createElement("name");
    Text nametextNode = doc.createTextNode(name);
    nameNode.appendChild(nametextNode);
    Element phoneNode = doc.createElement("phone");
    Text phonetextNode = doc.createTextNode(phone);
    phoneNode.appendChild(phonetextNode);
    
    Element personNode = doc.createElement("person");
    personNode.appendChild(nameNode);
    personNode.appendChild(phoneNode);
    return(personNode);
  }



  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: persionWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
    <person>
        <name>
            Fred
        </name>
        <phone>
            555-4927
        </phone>
    </person>
    <person>
        <name>
            Sam
        </name>
        <phone>
            555-9832
        </phone>
    </person>
</locations>


Editing the Text of a Node

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      modifyTextByReplacement(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void modifyTextByReplacement(Document doc) {
    Element root = doc.getDocumentElement();
    Element place = (Element)root.getFirstChild();
    Text name = (Text)place.getFirstChild().getFirstChild();
    Text directions = (Text)place.getLastChild().getFirstChild();
    name.setData("newName");
    directions.setData("newDirection");
  }


  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}



<?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            newName
        </name>
        <directions>
            newDirection
        </directions>
    </place>
</locations>


Edit Text by Insertion and Replacement

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      editTextbyInsertionandReplacement(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void editTextbyInsertionandReplacement(Document doc) {
    Element root = doc.getDocumentElement();
    Element place = (Element)root.getFirstChild();
    Text name = (Text)place.getFirstChild().getFirstChild();
    Text directions = (Text)place.getLastChild().getFirstChild();
    // Inserting the word "black"
//    name.insertData(offset," black");
    name.insertData(3," black");
    // Replace "left" with "right"
    //directions.replaceData(offset,count,"right");
    directions.replaceData(3,3,"right");
  }



  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>name</name>
        <directions>direction</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            old blackName
        </name>
        <directions>
            oldrightection
        </directions>
    </place>
</locations>


Inserting a CDATASection Node

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      addCDATA(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void addCDATA(Document doc) {
    Element root = doc.getDocumentElement();
    Element place = (Element)root.getFirstChild();
    Element directions = (Element)place.getLastChild();
    String dirtext = "cdData.";
    CDATASection dirdata = doc.createCDATASection(dirtext);
    directions.replaceChild(dirdata,directions.getFirstChild());
  }



  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>name</name>
        <directions>direction</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            oldName
        </name>
        <directions>
        </directions>
    </place>
</locations>


Inserting a Processing Instruction and Comment

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      addComment(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void addComment(Document doc) {
    Element root = doc.getDocumentElement();
    Element folks = (Element)root.getLastChild();
    Comment comment = doc.createComment("Text of the comment");
    root.insertBefore(comment,folks);
  }




  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: persionWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <!-- Text of the comment -->
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>


Locating a Node and Modifying Text

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      newEmail(doc, "B D",  "newEmail");
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void newEmail(Document doc,String newname,String newemail) {
    Element root = doc.getDocumentElement();
    NodeList rootlist = root.getChildNodes();
    for(int i=0; i<rootlist.getLength(); i++) {
        Element person = (Element)rootlist.item(i);
        NodeList personlist = person.getChildNodes();
        Element name = (Element)personlist.item(0);
        NodeList namelist = name.getChildNodes();
        Text nametext = (Text)namelist.item(0);
        String oldname = nametext.getData();
        if(oldname.equals(newname)) {
            Element email = (Element)personlist.item(1);
            NodeList emaillist = email.getChildNodes();
            Text emailtext = (Text)emaillist.item(0);
            emailtext.setData(newemail);
        }
    }
}

  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person>
        <name>
            B D
        </name>
        <phone>
            newEmail
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


Locating a Node by an ID

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      findByID(doc, "B");
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void findByID(Document doc,String idName) {
    Element name = doc.getElementById(idName);
    if(name == null) {
        System.out.println("There is no element with the ID "
                + idName);
    } else {
        Text text = (Text)name.getFirstChild();
        System.out.println("The ID " + idName
                + " locates the name " + text.getData());
    }
  }


  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}



The ID B locates the name BB


Locating a Node by Using Siblings

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      newEmail(doc, "B D", "newEmail");
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void newEmail(Document doc, String newname, String newemail) {
    Element root = doc.getDocumentElement();
    Element person = (Element) root.getFirstChild();
    while (person != null) {
      Element name = (Element) person.getFirstChild();
      Text nametext = (Text) name.getFirstChild();
      String oldname = nametext.getData();
      if (oldname.equals(newname)) {
        Element email = (Element) name.getNextSibling();
        Text emailtext = (Text) email.getFirstChild();
        emailtext.setData(newemail);
      }
      person = (Element) person.getNextSibling();
    }
  }
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>





Locating Elements by Tag Name

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      makeNamelist(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  private static void makeNamelist(Document doc) {
    String names = null;
    Element root = doc.getDocumentElement();
    NodeList nameElements = root.getElementsByTagName("name");
    for(int i=0; i<nameElements.getLength(); i++) {
        Element name = (Element)nameElements.item(i);
        Text nametext = (Text)name.getFirstChild();
        if(names == null){
            names = nametext.getData();
        }else{
            names += ", " + nametext.getData();
        }
    }
    Element namelist = doc.createElement("names");
    Text namelisttext = doc.createTextNode(names);
    namelist.appendChild(namelisttext);
    root.insertBefore(namelist,root.getFirstChild());
}
  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <names>
        B D
    </names>
    <person>
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


Methods to Insert a Processing Instruction and a Comment

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      addProcessingInstruction(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void addProcessingInstruction(Document doc) {
    Element root = doc.getDocumentElement();
    Element folks = (Element)root.getLastChild();
    ProcessingInstruction pi;
    pi = (ProcessingInstruction)doc.createProcessingInstruction(
        "validate",
        "phone=\"lookup\"");
    root.insertBefore(pi,folks);
  }




  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: persionWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <?validate phone="lookup"?>
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>


Modifying Text by Cutting and Pasting

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      modifyingTextbyCuttingandPasting(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void modifyingTextbyCuttingandPasting(Document doc) {
    Element root = doc.getDocumentElement();
    Element place = (Element)root.getFirstChild();
    Text name = (Text)place.getFirstChild().getFirstChild();
    Text directions = (Text)place.getLastChild().getFirstChild();
//    name.deleteData(offset,count);
    name.deleteData(2,3);
    
    //String bridge = directions.substringData(offset,count);
    String bridge = directions.substringData(2,3);
    name.appendData(bridge);
  }    



  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>name</name>
        <directions>direction</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            olmedDi
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>


Moving and Copying Attributes

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      dupAttributes(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void dupAttributes(Document doc) {
    Element root = doc.getDocumentElement();
    Element personOne = (Element)root.getFirstChild();
    Attr deptAttr = personOne.getAttributeNode("dept");
    personOne.removeAttributeNode(deptAttr);
    String deptString = deptAttr.getValue();
    personOne.setAttribute("dept",deptString+" updated");
    String mailString = personOne.getAttribute("mail");
    personOne.setAttribute("mail",mailString+" updated");
    
    String titleString = personOne.getAttribute("title");
    //personOne.removeAttribute("title");
    personOne.setAttribute("title",titleString+" updated");
}

  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: personDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ATTLIST person number CDATA #IMPLIED
                 dept CDATA #IMPLIED
                 mail CDATA #IMPLIED
                 title CDATA #IMPLIED>
]>
<folks>
    <person number="3412" dept="medical" mail="mailValue" title="titleValue">
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person dept="medical updated" mail="mailValue updated" number="3412" title="titleValue updated">
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


Moving Nodes between Documents: Copy a Node from One Parse Tree into Another

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      importName(doc, doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void importName(Document doc1,Document doc2) {
    Element root1 = doc1.getDocumentElement();
    Element personInDoc1 = (Element)root1.getFirstChild();
    Node importedPerson = doc2.importNode(personInDoc1,true);
    Element root2 = doc2.getDocumentElement();
    root2.appendChild(importedPerson);
  }



  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: persionWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>



<?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>


Normalize All of the Text in a Document

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      normalize(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void normalize(Document doc) {
    Element root = doc.getDocumentElement();
    root.normalize();
  }



  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE locations [
<!ELEMENT locations (place)*>
<!ELEMENT place (name | directions)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT directions (#PCDATA)>
]>
<locations>
    <place>
        <name>name</name>
        <directions>direction</directions>
    </place>
</locations>





Replacing a Tree Node: Replacing an Existing Node with a New One

/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002
*/

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      replacePerson(doc,"newName","111111","newEmail@email.ru");
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void replacePerson(Document doc, String name, String phone, String email) {
    Element newPersonNode = doc.createElement("person");
    Element nameNode = doc.createElement("name");
    newPersonNode.appendChild(nameNode);
    Text nametextNode = doc.createTextNode(name);
    nameNode.appendChild(nametextNode);
    Element phoneNode = doc.createElement("phone");
    newPersonNode.appendChild(phoneNode);
    Text phonetextNode = doc.createTextNode(phone);
    phoneNode.appendChild(phonetextNode);
    Element emailNode = doc.createElement("email");
    newPersonNode.appendChild(emailNode);
    Text emailtextNode = doc.createTextNode(email);
    emailNode.appendChild(emailtextNode);
    Element root = doc.getDocumentElement();
    Element oldPersonNode = (Element) root.getFirstChild();
    root.replaceChild(newPersonNode, oldPersonNode);
  }
  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>
<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>





Setting an Attribute

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.rument;
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.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);
      addAttribute(doc);
      write(doc);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  public static void addAttribute(Document doc) {
    Element root = doc.getDocumentElement();
    Element person = (Element)root.getFirstChild();
    person.setAttribute("company","yourCom");
  }

  
  
  
  
  
  
  
  
  
  
  
  
  private static final String TAB = "    ";
  private static void write(Document doc) throws IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement(), "");
  }
  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null) && (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      } else {
        System.out.println(" standalone=\"no\"?>");
      }
    } else {
      System.out.println("?>");
    }
  }
  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attr) nm.item(i);
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() + ">");
  }
  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }
  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData() );
  }
  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() + " -->");
  }
  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() + " " + node.getData() + "?>");
  }
  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Element) node, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Text) node, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASection) node, indent);
      break;
    case Node.ruMENT_NODE:
      outputComment((Comment) node, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstruction) node, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}
class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }
  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }
  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>
<!-- This document is both well formed and valid -->
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ATTLIST person number CDATA #IMPLIED
                 dept CDATA "staff">
]>
<folks>
    <person number="3412" dept="medical">
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>



<?xml version="1.0" standalone="yes"?>
<folks>
    <person company="yourCom" dept="medical" number="3412">
        <name>
            B D
        </name>
        <phone>
            999 555-8888
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>


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;
  }
}