Editing the Text of a Node : DOM Edit « XML « Java Tutorial

Java Tutorial
1. Language
2. Data Type
3. Operators
4. Statement Control
5. Class Definition
6. Development
7. Reflection
8. Regular Expressions
9. Collections
10. Thread
11. File
12. Generics
13. I18N
14. Swing
15. Swing Event
16. 2D Graphics
17. SWT
18. SWT 2D Graphics
19. Network
20. Database
21. JSP
22. JSTL
23. Servlet
24. Web Services SOA
25. Email
26. J2ME
27. J2EE Application
28. XML
29. Design Pattern
30. Log
31. Security
32. Apache Common
Java
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Tutorial » XML » DOM Edit 
28. 3. 14. 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.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);

      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 docthrows 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 = (Attrnm.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((Elementnode, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Textnode, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASectionnode, indent);
      break;
    case Node.COMMENT_NODE:
      outputComment((Commentnode, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstructionnode, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}

class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException ethrows SAXException {
    show("Warning", e);
    throw (e);
  }

  public void error(SAXParseException ethrows SAXException {
    show("Error", e);
    throw (e);
  }

  public void fatalError(SAXParseException ethrows 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>


    
        
            newName
        
        
            newDirection
        
    
28. 3. DOM Edit
28. 3. 1. Creating an XML Document from a DOM Tree
28. 3. 2. Adding a New Entry to the End of a List
28. 3. 3. A Method for Inserting a New Entry in a List
28. 3. 4. Locating a Node and Modifying Text
28. 3. 5. Locating a Node by Using Siblings
28. 3. 6. Deleting a Tree Node
28. 3. 7. Replacing a Tree Node: Replacing an Existing Node with a New One
28. 3. 8. Locating Elements by Tag Name
28. 3. 9. Duplicating a Portion of the Tree
28. 3. 10. Setting an Attribute
28. 3. 11. Deleting an Attribute
28. 3. 12. Moving and Copying Attributes
28. 3. 13. Locating a Node by an ID
28. 3. 14. Editing the Text of a Node
28. 3. 15. Modifying Text by Cutting and Pasting
28. 3. 16. Edit Text by Insertion and Replacement
28. 3. 17. Inserting a CDATASection Node
28. 3. 18. Normalize All of the Text in a Document
28. 3. 19. Moving Nodes between Documents: Copy a Node from One Parse Tree into Another
28. 3. 20. Editing by Using a Document Fragment: Creating a DocumentFragment Subtree and Appending to the Document
28. 3. 21. Inserting a Processing Instruction and Comment
28. 3. 22. Methods to Insert a Processing Instruction and a Comment
ww__w__.___ja___v_a__2s__.__co_m | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.