Search element by name using DOM in Java

Description

The following code shows how to search element by name using DOM.

Example


import java.io.StringReader;
import java.io.StringWriter;
/* w w w.j av  a 2 s .  c o  m*/
import javax.xml.parsers.DocumentBuilder;
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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

public class Main {
  static public void main(String[] arg) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = dbf.newDocumentBuilder();

    Document document = builder.parse(new InputSource("yourfile.xml"));
    newEmail(document, "newName", "java2s.com");
    
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    StringWriter sw = new StringWriter();
    trans.transform(new DOMSource(document), new StreamResult(sw));
    System.out.println(sw.toString());


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




















Home »
  Java Tutorial »
    XML »




DOM
SAX