Locating a Node and Modifying Text : DOM Edit « XML « Java Tutorial






/*
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.Comment;
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.COMMENT_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>


    
        
            B D
        
        
            newEmail
        
        
            b@xyz.net
        
    








33.3.DOM Edit
33.3.1.Creating an XML Document from a DOM Tree
33.3.2.Create Document with root QName
33.3.3.Create New Container
33.3.4.Document To String
33.3.5.Start a new XML Document
33.3.6.Adding a New Entry to the End of a List
33.3.7.A Method for Inserting a New Entry in a List
33.3.8.Locating a Node and Modifying Text
33.3.9.Locating a Node by Using Siblings
33.3.10.Deleting a Tree Node
33.3.11.Replacing a Tree Node: Replacing an Existing Node with a New One
33.3.12.Locating Elements by Tag Name
33.3.13.Duplicating a Portion of the Tree
33.3.14.Setting an Attribute
33.3.15.Deleting an Attribute
33.3.16.Moving and Copying Attributes
33.3.17.Locating a Node by an ID
33.3.18.Editing the Text of a Node
33.3.19.Modifying Text by Cutting and Pasting
33.3.20.Edit Text by Insertion and Replacement
33.3.21.Inserting a CDATASection Node
33.3.22.Normalize All of the Text in a Document
33.3.23.Moving Nodes between Documents: Copy a Node from One Parse Tree into Another
33.3.24.Editing by Using a Document Fragment: Creating a DocumentFragment Subtree and Appending to the Document
33.3.25.Inserting a Processing Instruction and Comment
33.3.26.Methods to Insert a Processing Instruction and a Comment
33.3.27.Changing the Name of a DOM Element