Edit DOM Using a Document Fragment in Java

Description

The following code shows how to edit DOM Using a Document Fragment.

Example


/*ww  w .  j a  v a 2  s . c o  m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

public class Main {
  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();
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);

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

}
<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>
       
   ]]>
</code>
<result><![CDATA[    
  <?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>




















Home »
  Java Tutorial »
    XML »




DOM
SAX