Java/XML/DOM Edit

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

Содержание

Add a comment at the beginning of the document

   <source lang="java">
    

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.rument; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class Main {

 public static void main(String[] argv) throws Exception {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   factory.setValidating(true);
   factory.setExpandEntityReferences(false);
   Document doc = factory.newDocumentBuilder().parse(new File("filename"));
   Element element = doc.getDocumentElement();
   Comment comment = doc.createComment("A Document Comment");
   element.getParentNode().insertBefore(comment, element);
 }

}



 </source>
   
  
 
  



A Method for Inserting a New Entry in a List

   <source lang="java">
    
   public void insertPerson(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);
   }




 </source>
   
  
 
  



Change a particular node in XML

   <source lang="java">
    

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class Main {

 public static void main(String[] args) throws Exception {
   Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
       new InputSource("data.xml"));
   XPath xpath = XPathFactory.newInstance().newXPath();
   NodeList nodes = (NodeList) xpath.evaluate("//employee/name[text()="old"]", doc,
       XPathConstants.NODESET);
   for (int idx = 0; idx < nodes.getLength(); idx++) {
     nodes.item(idx).setTextContent("new value");
   }
   Transformer xformer = TransformerFactory.newInstance().newTransformer();
   xformer.transform(new DOMSource(doc), new StreamResult(new File("data_new.xml")));
 }

}



 </source>
   
  
 
  



Copies the source tree into the specified place in a destination tree.

   <source lang="java">
  

import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.sun.org.apache.xerces.internal.dom.AttrImpl; import com.sun.org.apache.xerces.internal.dom.DocumentImpl; /*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

public class Main {

 /**
  * Copies the source tree into the specified place in a destination
  * tree. The source node and its children are appended as children
  * of the destination node.
*

* Note: This is an iterative implementation. */ public static void copyInto(Node src, Node dest) throws DOMException { // get node factory Document factory = dest.getOwnerDocument(); boolean domimpl = factory instanceof DocumentImpl; // placement variables Node start = src; Node parent = src; Node place = src; // traverse source tree while (place != null) { // copy this node Node node = null; int type = place.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: { node = factory.createCDATASection(place.getNodeValue()); break; } case Node.ruMENT_NODE: { node = factory.createComment(place.getNodeValue()); break; } case Node.ELEMENT_NODE: { Element element = factory.createElement(place.getNodeName()); node = element; NamedNodeMap attrs = place.getAttributes(); int attrCount = attrs.getLength(); for (int i = 0; i < attrCount; i++) { Attr attr = (Attr)attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); element.setAttribute(attrName, attrValue); if (domimpl && !attr.getSpecified()) { ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false); } } break; } case Node.ENTITY_REFERENCE_NODE: { node = factory.createEntityReference(place.getNodeName()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue()); break; } case Node.TEXT_NODE: { node = factory.createTextNode(place.getNodeValue()); break; } default: { throw new IllegalArgumentException("can"t copy node type, "+ type+" ("+ node.getNodeName()+")"); } } dest.appendChild(node); // iterate over children if (place.hasChildNodes()) { parent = place; place = place.getFirstChild(); dest = node; } // advance else { place = place.getNextSibling(); while (place == null && parent != start) { place = parent.getNextSibling(); parent = parent.getParentNode(); dest = dest.getParentNode(); } } } } // copyInto(Node,Node) } </source>

Copy a Node from one source document

   <source lang="java">
 

import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; public class Utils {

 /**
  * Copy a Node from one source document, adding it to the document
  * root of a different, target Document
  * @param source Document to copy
  * @param target Document to contain copy
  */
 public static void copyDocumentNode(Node source, Document target)
 {
   Node node = target.importNode(source, true);
   target.getDocumentElement().appendChild(node);
 }

}


 </source>
   
  
 
  



Create a new element and move the middle text node to it

   <source lang="java">
    

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; 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();
   Text text1 = (Text) element.getFirstChild();
   String string = text1.getData();
   String word = "some";
   Text text2 = text1.splitText(string.indexOf(word));
   
   Element newElement = doc.createElement("b");
   newElement.appendChild(text2);
 }

}



 </source>
   
  
 
  



Creates element node, attribute node, comment node, processing instruction and a CDATA section

   <source lang="java">
    
      

/***************************************************************

* (C) Copyright 2002 by Deitel & Associates, Inc. and         *
* Prentice Hall. All Rights Reserved.                         *
*                                                             *
* DISCLAIMER: The authors and publisher of this book have     *
* used their best efforts in preparing the book. These        *
* efforts include the development, research, and testing of   *
* the theories and programs to determine their effectiveness. *
* The authors and publisher make no warranty of any kind,     *
* expressed or implied, with regard to these programs or to   *
* the documentation contained in these books. The authors     *
* and publisher shall not be liable in any event for          *
* incidental or consequential damages in connection with, or  *
* arising out of, the furnishing, performance, or use of      *
* these programs.                                             *
***************************************************************/
      

import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.rument; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; public class BuildXml {

 private Document document;
 public BuildXml() {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   try {
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.newDocument();
   }catch (ParserConfigurationException parserException) {
     parserException.printStackTrace();
   }
   Element root = document.createElement("root");
   document.appendChild(root);
   // add comment to XML document
   Comment simpleComment = document.createComment("This is a simple contact list");
   root.appendChild(simpleComment);
   // add child element
   Node contactNode = createContactNode(document);
   root.appendChild(contactNode);
   // add processing instruction
   ProcessingInstruction pi = document.createProcessingInstruction("myInstruction",
       "action silent");
   root.appendChild(pi);
   // add CDATA section
   CDATASection cdata = document.createCDATASection("I can add <, >, and ?");
   root.appendChild(cdata);
   // write the XML document to disk
   try {
     // create DOMSource for source XML document
     Source xmlSource = new DOMSource(document);
     // create StreamResult for transformation result
     Result result = new StreamResult(new FileOutputStream("myDocument.xml"));
     // create TransformerFactory
     TransformerFactory transformerFactory = TransformerFactory.newInstance();
     // create Transformer for transformation
     Transformer transformer = transformerFactory.newTransformer();
     transformer.setOutputProperty("indent", "yes");
     // transform and deliver content to client
     transformer.transform(xmlSource, result);
   }
   // handle exception creating TransformerFactory
   catch (TransformerFactoryConfigurationError factoryError) {
     System.err.println("Error creating " + "TransformerFactory");
     factoryError.printStackTrace();
   }catch (TransformerException transformerError) {
     System.err.println("Error transforming document");
     transformerError.printStackTrace();
   }    catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
 public Node createContactNode(Document document) {
   // create FirstName and LastName elements
   Element firstName = document.createElement("FirstName");
   Element lastName = document.createElement("LastName");
   firstName.appendChild(document.createTextNode("First Name"));
   lastName.appendChild(document.createTextNode("Last Name"));
   // create contact element
   Element contact = document.createElement("contact");
   // create attribute
   Attr genderAttribute = document.createAttribute("gender");
   genderAttribute.setValue("F");
   // append attribute to contact element
   contact.setAttributeNode(genderAttribute);
   contact.appendChild(firstName);
   contact.appendChild(lastName);
   return contact;
 }
 public static void main(String args[]) {
   BuildXml buildXml = new BuildXml();
 }

}




 </source>
   
  
 
  



Generates a DOM from scratch. Writes the DOM to a String using an LSSerializer.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; /**

* Simple Sample that: - Generates a DOM from scratch. - Writes the DOM to a
* String using an LSSerializer
* 
* @author Jeffrey Rodriguez
* @version $Id: DOMGenerate.java 546623 2007-06-12 20:25:08Z mrglavas $
*/

public class DOMGenerate {

 public static void main(String[] argv) {
   try {
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setNamespaceAware(true);
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.newDocument();
     Element root = doc.createElementNS(null, "person"); // Create Root Element
     Element item = doc.createElementNS(null, "name"); // Create element
     item.appendChild(doc.createTextNode("Jeff"));
     root.appendChild(item); // Attach element to Root element
     item = doc.createElementNS(null, "age"); // Create another Element
     item.appendChild(doc.createTextNode("28"));
     root.appendChild(item); // Attach Element to previous element down tree
     item = doc.createElementNS(null, "height");
     item.appendChild(doc.createTextNode("1.80"));
     root.appendChild(item); // Attach another Element - grandaugther
     doc.appendChild(root); // Add Root to Document
     DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
     DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
     LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer
                                                         // for the DOM
     LSOutput out = domImplLS.createLSOutput();
     StringWriter stringOut = new StringWriter(); // Writer will be a String
     out.setCharacterStream(stringOut);
     ser.write(doc, out); // Serialize the DOM
     System.out.println("STRXML = " + stringOut.toString()); // Spit out the
                                                             // DOM as a String
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }

}

 </source>
   
  
 
  



Insert the new element where the middle node used to be

   <source lang="java">
    

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; 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();
   Text text1 = (Text) element.getFirstChild();
   String string = text1.getData();
   String word = "some";
   Text text2 = text1.splitText(string.indexOf(word));
   Element newElement = doc.createElement("b");
   newElement.appendChild(text2);
   element.insertBefore(newElement, text2);
 }

}



 </source>
   
  
 
  



Java DOM edit: Add an Element Containing All Names

   <source lang="java">
    
   private 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("namelist");
       Text namelisttext = doc.createTextNode(names);
       namelist.appendChild(namelisttext);
       root.insertBefore(namelist,root.getFirstChild());
   }

}




 </source>
   
  
 
  



Java DOM edit: Adding an Attribute to an Element

   <source lang="java">
    
   public void addAttribute(Document doc) {
       Element root = doc.getDocumentElement();
       Element person = (Element)root.getFirstChild();
       person.setAttribute("company","CastleWorks");
   }




 </source>
   
  
 
  



Java DOM edit: A Method to Find an ID Value and Print the Element Text

   <source lang="java">
    

//An XML Document with ID Tags on Names /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE folks [ <!ELEMENT folks (person)*> <!ELEMENT person (name)> <!ELEMENT name (#PCDATA)> <!ATTLIST name nick ID #IMPLIED> ]> <folks>

   <person>
       <name nick="Al">Alite Quandry</name>
   </person>
   <person>
       <name nick="Fred">Mush Pushkin</name>
   </person>
   <person>
       <name nick="Alvie">Avarine Spraddle</name>
   </person>

</folks>

  • /
   public 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());
       }
   }
          
        
   
   
   
   
 </source>
   
  
 
  



Java DOM edit: Copy a Node from One Parse Tree into Another

   <source lang="java">
    

//An XML Document Providing an Element for Export /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE contacts [ <!ELEMENT contacts (person)*> <!ELEMENT person (name, email)> <!ELEMENT name (#PCDATA | bold)*> <!ELEMENT email (#PCDATA)> ]> <contacts>

   <person>
       <name>Ichobad Crane</name>
       <email>sleepy@hollow.net</email>
   </person>

</contacts>*/ //An XML Document to Receive an Imported Element /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE folks [ <!ELEMENT folks (person)*> <!ELEMENT person (name, phone, email)> <!ELEMENT name (#PCDATA | bold)*> <!ELEMENT phone (#PCDATA)> <!ELEMENT email (#PCDATA)> ]> <folks>

   <person>
       <name>Zaphod Beeblebrox</name>
       <phone>907 555-9882</phone>
       <email>outer@space.net</email>
   </person>

</folks>

  • /

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.*; public class DOMImport {

   static public void main(String[] arg) {
       if(arg.length != 3) {
           System.err.println(
                   "Usage: DOMImport <infile1> <infile2> <outfile>");
           System.exit(1);
       }
       DOMImport dc = new DOMImport();
       dc.inandout(arg[0],arg[1],arg[2]);
   }
   public void inandout(String infile1,String infile2,String outfile) {
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       dbf.setValidating(true);
       dbf.setNamespaceAware(true);
       dbf.setIgnoringElementContentWhitespace(true);
       Document doc1 = null;
       Document doc2 = null;
       try {
           DocumentBuilder builder = dbf.newDocumentBuilder();
           builder.setErrorHandler(new MyErrorHandler());
           InputSource is1 = new InputSource(infile1);
           doc1 = builder.parse(is1);
           InputSource is2 = new InputSource(infile2);
           doc2 = builder.parse(is2);
           importName(doc1,doc2);
           FileOutputStream fos = new FileOutputStream(outfile);
           TreeToXML ttxml = new TreeToXML();
           ttxml.write(fos,doc2);
           fos.close();
       } catch (SAXException e) {
           System.exit(1);
       } catch (ParserConfigurationException e) {
           System.err.println(e);
           System.exit(1);
       } catch (IOException e) {
           System.err.println(e);
           System.exit(1);
       }
   }
   public 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);
   }

}




 </source>
   
  
 
  



Java DOM edit: Copying Attributes

   <source lang="java">
    
   public void dupAttributes(Document doc) {
       Element root = doc.getDocumentElement();
       Element personOne = (Element)root.getFirstChild();
       Element personTwo = (Element)personOne.getNextSibling();
       Element personThree = (Element)personTwo.getNextSibling();
       Attr deptAttr = personOne.getAttributeNode("dept");
       personOne.removeAttributeNode(deptAttr);
       String deptString = deptAttr.getValue();
       personTwo.setAttribute("dept",deptString);
       personThree.setAttribute("dept",deptString);
       String mailString = personOne.getAttribute("mail");
       personTwo.setAttribute("mail",mailString);
       
       String titleString = personOne.getAttribute("title");
       personOne.removeAttribute("title");
       personThree.setAttribute("title",titleString);
   }




 </source>
   
  
 
  



Java DOM edit: Creates a New DOM Parse Tree

   <source lang="java">
    

import java.io.FileOutputStream; import java.io.IOException; 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.Text; public class DOMNew {

 static public void main(String[] arg) {
   if (arg.length != 1) {
     System.err.println("Usage: DOMNew <outfile>");
     System.exit(1);
   }
   DOMNew dc = new DOMNew();
   dc.createNew(arg[0]);
 }
 public void createNew(String outfile) {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   dbf.setValidating(true);
   dbf.setNamespaceAware(true);
   dbf.setIgnoringElementContentWhitespace(true);
   Document doc = null;
   try {
     DocumentBuilder builder = dbf.newDocumentBuilder();
     doc = builder.newDocument();
     buildTree(doc);
     FileOutputStream fos = new FileOutputStream(outfile);
     TreeToXML ttxml = new TreeToXML();
     ttxml.write(fos, doc);
     fos.close();
   } catch (ParserConfigurationException e) {
     System.err.println(e);
     System.exit(1);
   } catch (IOException e) {
     System.err.println(e);
     System.exit(1);
   }
 }
 public void buildTree(Document doc) {
   Element name;
   Text text;
   Element root = doc.createElement("places");
   doc.appendChild(root);
   name = doc.createElement("name");
   text = doc.createTextNode("Algonquin Roundtable");
   name.appendChild(text);
   root.appendChild(name);
   name = doc.createElement("name");
   text = doc.createTextNode("Bayou Teche");
   name.appendChild(text);
   root.appendChild(name);
 }

}




 </source>
   
  
 
  



Java DOM edit: Creating a DocumentFragment Subtree and Appending to the Document

   <source lang="java">
    

//A Document Containing a Single Person Node /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE folks [ <!ELEMENT folks (person)*> <!ELEMENT person (name, phone)> <!ELEMENT name (#PCDATA | bold)*> <!ELEMENT phone (#PCDATA)> ]> <folks>

   <person>
       <name>Frank Fangston</name>
       <phone>555-3247</phone>
   </person>

</folks>

  • /
   public void addFragment(Document doc) {
       Element person;
       Element root = doc.getDocumentElement();
       DocumentFragment fragment = doc.createDocumentFragment();
       person = makePersonNode(doc,"Fred","555-4927");
       fragment.appendChild(person);
       person = makePersonNode(doc,"Sam","555-9832");
       fragment.appendChild(person);
       root.appendChild(fragment);
   }
   private 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);
   }




 </source>
   
  
 
  



Java DOM edit: Delete the First Child of the Root Node

   <source lang="java">
    
   public void deleteFirstElement(Document doc) {
       Element root = doc.getDocumentElement();
       Element child = (Element)root.getFirstChild();
       root.removeChild(child);
   }
          
        
   
   
   
   
 </source>
   
  
 
  



Java DOM edit: Deleting Two Attributes

   <source lang="java">
    

//An XML Document Containing Two Attributes /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE folks [ <!ELEMENT folks (person)*> <!ELEMENT person (name | email)*> <!ELEMENT name (#PCDATA)> <!ELEMENT email (#PCDATA)> <!ATTLIST person extension CDATA #IMPLIED

                dept CDATA "staff">

]> <folks>

   <person extension="3412" dept="medical">
       <name>Doctor Polidori</name>
       <email>deft@jerk.net</email>
   </person>

</folks>

  • /
   public void delAttribute(Document doc) {
       Element root = doc.getDocumentElement();
       Element person = (Element)root.getFirstChild();
       person.removeAttribute("extension");
       person.removeAttribute("dept");
   }
          
        
   
   
   
   
 </source>
   
  
 
  



Java DOM edit: Duplicate a Subtree

   <source lang="java">
    
   public void duplicatePerson(Document doc) {
       Element root = doc.getDocumentElement();
       Element origPerson = (Element)root.getFirstChild();
       Element newPerson = (Element)origPerson.cloneNode(true);
       root.appendChild(newPerson);
   }




 </source>
   
  
 
  



Java DOM edit: Edit Text by Insertion and Replacement

   <source lang="java">
    
   public void edit3(Document doc) {
       int count;
       int offset;
       Element root = doc.getDocumentElement();
       Element place = (Element)root.getFirstChild();
       Text name = (Text)place.getFirstChild().getFirstChild();
       Text directions = (Text)place.getLastChild().getFirstChild();
       offset = 7;
       name.insertData(offset," black");
       offset = 5;
       count = 4;
       directions.replaceData(offset,count,"right");
   }




 </source>
   
  
 
  



Java DOM edit: Insert a Processing Instruction and a Comment

   <source lang="java">
    
   public 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);
   }
   public 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);
   }




 </source>
   
  
 
  



Java DOM edit: Locate a Node and Change Its Content

   <source lang="java">
    

//Demo xml file /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE folks [ <!ELEMENT folks (person)*> <!ELEMENT person (name | phone | email)*> <!ELEMENT name (#PCDATA | bold)*> <!ELEMENT phone (#PCDATA)> <!ELEMENT email (#PCDATA)> <!ELEMENT bold (#PCDATA)> ]> <folks>

   <person>
       <name>Sam Spade</name>
       <email>samspade@website.ru</email>
   </person>
   <person>
       <name>Sam Diamond</name>
       <email>samdiamond@website.ru</email>
   </person>
   <person>
       <name>Sam Sonite</name>
       <email>samsonite@website.ru</email>
   </person>

</folks>

  • /

public void changeContent(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);
       }
   }

}




 </source>
   
  
 
  



Java DOM edit: Locating a Node by Using Siblings

   <source lang="java">
    
   public void LocatingUsingSibling(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();
       }
   }
          
        
   
   
   
   
 </source>
   
  
 
  



Java DOM edit: Modifying Text by Cutting and Pasting

   <source lang="java">
    
   public void edit(Document doc) {
       int length;
       int count;
       int offset;
       Element root = doc.getDocumentElement();
       Element place = (Element)root.getFirstChild();
       Text name = (Text)place.getFirstChild().getFirstChild();
       Text directions = (Text)place.getLastChild().getFirstChild();
       length = name.getLength();
       count = 4;
       offset = length - 4;
       name.deleteData(offset,count);
       length = directions.getLength();
       count = 6;
       offset = length - count;
       String bridge = directions.substringData(offset,count);
       name.appendData(bridge);
       count = 5;
       offset = 4;
       directions.deleteData(offset,count);
   }




 </source>
   
  
 
  



Java DOM edit: Modifying Text by Replacement

   <source lang="java">
    

//A Document with Two Simple Text Nodes /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE locations [ <!ELEMENT locations (place)*> <!ELEMENT place (name | directions)*> <!ELEMENT name (#PCDATA)> <!ELEMENT directions (#PCDATA)> ]> <locations>

   <place>
       <name>Fishing hole</name>
       <directions>Turn left at bridge</directions>
   </place>

</locations>

  • /
   public void edit(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("AAA");
       directions.setData("BBB");
   }




 </source>
   
  
 
  



Java DOM edit: Normalize All of the Text in a Document

   <source lang="java">
    
   public void normalize(Document doc) {
       Element root = doc.getDocumentElement();
       root.normalize();
   }
          
        
   
   
   
   
 </source>
   
  
 
  



Java DOM edit: Replacing an Existing Node with a New One

   <source lang="java">
    
   public 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);
   }
          
        
   
   
   
   
 </source>
   
  
 
  



Java DOM edit: Replacing a Text Node with a New CDATASection Node

   <source lang="java">
    
   public void addCDATA(Document doc) {
       Element root = doc.getDocumentElement();
       Element place = (Element)root.getFirstChild();
       Element directions = (Element)place.getLastChild();
       String dirtext =
           ">>>\n" +
           "<<<\n" +
           "&&&\n" +
           "<><><>.";
       CDATASection dirdata = doc.createCDATASection(dirtext);
       directions.replaceChild(dirdata,directions.getFirstChild());
   }




 </source>
   
  
 
  



Java DOM edit: Splitting One Text Node into Three

   <source lang="java">
    

//An Element with a Single Block of Text /* <?xml version="1.0" standalone="yes"?> <!DOCTYPE story [ <!ELEMENT story (paragraph)*> <!ELEMENT paragraph (#PCDATA)> ]> <story>

   <paragraph>Once upon a time</paragraph>

</story>

  • /
   public void split(Document doc) {
       Element root = doc.getDocumentElement();
       Element paragraph = (Element)root.getFirstChild();
       Text text = (Text)paragraph.getFirstChild();
       Text newText = text.splitText(20);
       newText.splitText(50);
   }




 </source>
   
  
 
  



Set text in a Node

   <source lang="java">
  

/*

* Copyright (C) 2001  Christian Cryder [christianc@granitepeaks.ru]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
* $Id: DOMUtil.java 114 2005-12-09 15:51:51Z christianc $
*/

import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; import org.w3c.dom.rument; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; /**

* DOM related utility functions.
*/

public class DOMUtil {

   private static byte[] sep = System.getProperty("line.separator").getBytes();
   /**
    * Find the first text descendent node of an element.
    * This recursively looks more than one level to search
    * for text in font nodes, etc.
    *
    * @param node The starting node for the search.
    * @return The text node or null if not found.
    */
   public static Text findFirstText(Node node) {
       if (node instanceof Text) return (Text) node;
       for (Node child = node.getFirstChild(); child!=null; child = child.getNextSibling()) {
           Text text = findFirstText(child);
           if (text!=null) return text;
       }
       return null;
   }
   /**
    * Gets the first text descendent node of an element.
    * This recursively looks more than one level to search
    * for text in font nodes, etc. Throws a DOMException
    * if the Text object is not found.
    *
    * @param node The starting node for the search.
    * @return The text node or null if not found.
    * @throws DOMException if the Text object is not found
    */
   public static Text getFirstText(Node node) {
       Text text = findFirstText(node);
       if (text==null) {
           String msg = "No child text mode found for element";
           String id = getID(node);
           throw new DOMException((short) -1, msg+(id!=null ? "; id=\""+id+"\"" : ""));
       }
       return text;
   }
   /**
    * Automatically set text in a Node. Basically we find the first
    * Text node beneath the current node and replace it with a
    * CDATASection for the incoming text. All other Text nodes are
    * removed. Throws a DOMException if it"s illegal to add a Text
    * child to the particular node.
    *
    * @param node the starting node for the search.
    * @param text the text to be set
    * @param allowMarkupInText whether to allow markup in text to pass through unparsed
    * @return the updated node
    * @throws DOMException if the Text object is not found
    */
   public static Node setTextInNode(Node node, String text, boolean allowMarkupInText) {
       //start by setting the value in the first text node we find with a comment
       Comment comment = node.getOwnerDocument().createComment("");
       Node newNode = null;
       
       //csc_092701.1 - support both encoded/unencoded text
       if (allowMarkupInText) newNode = node.getOwnerDocument().createCDATASection(text);
       else newNode = node.getOwnerDocument().createTextNode(text);

//System.out.println ("newNode: "+newNode);

       Text textComp = DOMUtil.findFirstText((Element) node);

//System.out.println ("textComp:"+textComp);

       if (textComp==null) {
           node.appendChild(comment);
       } else {
           Node parent = textComp.getParentNode();
           parent.replaceChild(comment, textComp);
       }
       
       //now remove all the rest of the text nodes
       removeAllTextNodes(node);        
       //now replace the comment with the newNode
       Node parent = comment.getParentNode();
       parent.replaceChild(newNode, comment);

//System.out.println ("parent: "+parent); //System.out.println ("result: "+DOMUtil.findFirstText((Element) parent)); //DOMUtil.printStackTrace(parent.getOwnerDocument().getDocumentElement());

       return node;
   }
   
   /**
    * Remove all text nodes below this node
    *
    * @param node The starting node for the search.
    */
   public static void removeAllTextNodes(Node node) {
       if (node==null) return;
       if (!node.hasChildNodes()) return;
       NodeList nl = node.getChildNodes();
       for (int i=nl.getLength()-1; i>=0; i--) {
           Node n = (Node) nl.item(i);        
           if (n instanceof Text) node.removeChild(n);
           else removeAllTextNodes(n);
       }
   }
   
   /**
    * Given a Node name, return the "id" attribute if it exists.
    * If it does not exist, return null instead. This is basically
    * just a convenience method to cast the node to element and 
    * return the id from that.
    *
    * @param node the node name in question
    * @return the id value for the given node, if it exists. null if 
    *        doesn"t
    */
   public static String getID(Node node) {
       return getID(node, null);
   }
   /**
    * Given a Node, return the "id" attribute if it exists.
    * If it does not exist, return nullResponse instead. This is basically
    * just a convenience method to cast the node to element and 
    * return the id from that.
    *
    * @param node the node in question
    * @param nullResponse the response to be returned if the id attribute
    *        does not exist
    * @return the id value for the given node, if it exists. null if 
    *        doesn"t
    */
   public static String getID(Node node, String nullResponse) {
       String nodeName = nullResponse;
       if (node instanceof Element) {
           nodeName = ((Element) node).getAttribute("id");
       }
       return nodeName;
   }
   protected static void print(OutputStream out, String s) {
       if (out!=null) try {
           out.write(s.getBytes());
           out.write(sep);
       } catch (IOException ioe) {}
   }

}


 </source>
   
  
 
  



XML Tree Dumper 2

   <source lang="java">
    

//Example XML document /*

An XML Document Containing a Simple Contact List

Start example <?xml version="1.0" standalone="yes"?> <folks>

   <person>
       <phone>306 555-9999</phone>
       <email>joe@webserver.net</email>
       <name>Wang, Joe</name>
   </person>
   <person>
       <phone>704 555-0000</phone>
       <name>Pet, Rob</name>
       <email>rob@server.ru</email>
   </person>

</folks>

  • /

import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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.Entity; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Notation; 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 TreeDumper2 {

 public void dump(Document doc) {
   dumpLoop((Node) doc, "");
 }
 private void dumpLoop(Node node, String indent) {
   switch (node.getNodeType()) {
   case Node.ATTRIBUTE_NODE:
     dumpAttributeNode((Attr) node, indent);
     break;
   case Node.CDATA_SECTION_NODE:
     dumpCDATASectionNode((CDATASection) node, indent);
     break;
   case Node.ruMENT_NODE:
     dumpCommentNode((Comment) node, indent);
     break;
   case Node.DOCUMENT_NODE:
     dumpDocument((Document) node, indent);
     break;
   case Node.DOCUMENT_FRAGMENT_NODE:
     dumpDocumentFragment((DocumentFragment) node, indent);
     break;
   case Node.DOCUMENT_TYPE_NODE:
     dumpDocumentType((DocumentType) node, indent);
     break;
   case Node.ELEMENT_NODE:
     dumpElement((Element) node, indent);
     break;
   case Node.ENTITY_NODE:
     dumpEntityNode((Entity) node, indent);
     break;
   case Node.ENTITY_REFERENCE_NODE:
     dumpEntityReferenceNode((EntityReference) node, indent);
     break;
   case Node.NOTATION_NODE:
     dumpNotationNode((Notation) node, indent);
     break;
   case Node.PROCESSING_INSTRUCTION_NODE:
     dumpProcessingInstructionNode((ProcessingInstruction) node, indent);
     break;
   case Node.TEXT_NODE:
     dumpTextNode((Text) node, indent);
     break;
   default:
     System.out.println(indent + "Unknown node");
     break;
   }
   NodeList list = node.getChildNodes();
   for (int i = 0; i < list.getLength(); i++)
     dumpLoop(list.item(i), indent + "   ");
 }
 /* Display the contents of a ATTRIBUTE_NODE */
 private void dumpAttributeNode(Attr node, String indent) {
   System.out.println(indent + "ATTRIBUTE " + node.getName() + "=\""
       + node.getValue() + "\"");
 }
 /* Display the contents of a CDATA_SECTION_NODE */
 private void dumpCDATASectionNode(CDATASection node, String indent) {
   System.out.println(indent + "CDATA SECTION length=" + node.getLength());
   System.out.println(indent + "\"" + node.getData() + "\"");
 }
 /* Display the contents of a COMMENT_NODE */
 private void dumpCommentNode(Comment node, String indent) {
   System.out.println(indent + "COMMENT length=" + node.getLength());
   System.out.println(indent + "  " + node.getData());
 }
 /* Display the contents of a DOCUMENT_NODE */
 private void dumpDocument(Document node, String indent) {
   System.out.println(indent + "DOCUMENT");
 }
 /* Display the contents of a DOCUMENT_FRAGMENT_NODE */
 private void dumpDocumentFragment(DocumentFragment node, String indent) {
   System.out.println(indent + "DOCUMENT FRAGMENT");
 }
 /* Display the contents of a DOCUMENT_TYPE_NODE */
 private void dumpDocumentType(DocumentType node, String indent) {
   System.out.println(indent + "DOCUMENT_TYPE: " + node.getName());
   if (node.getPublicId() != null)
     System.out.println(indent + " Public ID: " + node.getPublicId());
   if (node.getSystemId() != null)
     System.out.println(indent + " System ID: " + node.getSystemId());
   NamedNodeMap entities = node.getEntities();
   if (entities.getLength() > 0) {
     for (int i = 0; i < entities.getLength(); i++) {
       dumpLoop(entities.item(i), indent + "  ");
     }
   }
   NamedNodeMap notations = node.getNotations();
   if (notations.getLength() > 0) {
     for (int i = 0; i < notations.getLength(); i++)
       dumpLoop(notations.item(i), indent + "  ");
   }
 }
 /* Display the contents of a ELEMENT_NODE */
 private void dumpElement(Element node, String indent) {
   System.out.println(indent + "ELEMENT: " + node.getTagName());
   NamedNodeMap nm = node.getAttributes();
   for (int i = 0; i < nm.getLength(); i++)
     dumpLoop(nm.item(i), indent + "  ");
 }
 /* Display the contents of a ENTITY_NODE */
 private void dumpEntityNode(Entity node, String indent) {
   System.out.println(indent + "ENTITY: " + node.getNodeName());
 }
 /* Display the contents of a ENTITY_REFERENCE_NODE */
 private void dumpEntityReferenceNode(EntityReference node, String indent) {
   System.out.println(indent + "ENTITY REFERENCE: " + node.getNodeName());
 }
 /* Display the contents of a NOTATION_NODE */
 private void dumpNotationNode(Notation node, String indent) {
   System.out.println(indent + "NOTATION");
   System.out.print(indent + "  " + node.getNodeName() + "=");
   if (node.getPublicId() != null)
     System.out.println(node.getPublicId());
   else
     System.out.println(node.getSystemId());
 }
 /* Display the contents of a PROCESSING_INSTRUCTION_NODE */
 private void dumpProcessingInstructionNode(ProcessingInstruction node,
     String indent) {
   System.out.println(indent + "PI: target=" + node.getTarget());
   System.out.println(indent + "  " + node.getData());
 }
 /* Display the contents of a TEXT_NODE */
 private void dumpTextNode(Text node, String indent) {
   System.out.println(indent + "TEXT length=" + node.getLength());
   System.out.println(indent + "  " + node.getData());
 }
 static public void main(String[] arg) {
   String filename = null;
   boolean validate = false;
   if (arg.length == 1) {
     filename = arg[0];
   } else if (arg.length == 2) {
     if (!arg[0].equals("-v"))
       usage();
     validate = true;
     filename = arg[1];
   } else {
     usage();
   }
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   dbf.setValidating(validate);
   dbf.setNamespaceAware(true);
   dbf.setIgnoringElementContentWhitespace(true);
   // Parse the input to produce a parse tree with its root
   // in the form of a Document object
   Document doc = null;
   try {
     DocumentBuilder builder = dbf.newDocumentBuilder();
     builder.setErrorHandler(new MyErrorHandler());
     InputSource is = new InputSource(filename);
     doc = builder.parse(is);
   } catch (SAXException e) {
     System.exit(1);
   } catch (ParserConfigurationException e) {
     System.err.println(e);
     System.exit(1);
   } catch (IOException e) {
     System.err.println(e);
     System.exit(1);
   }
   // Use a TreeDumper to list the tree
   TreeDumper2 td = new TreeDumper2();
   td.dump(doc);
 }
 private static void usage() {
   System.err.println("Usage: DOMCheck [-v] <filename>");
   System.exit(1);
 }

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

}




 </source>