Insert a Processing Instruction to a DOM tree in Java

Description

The following code shows how to insert a Processing Instruction to a DOM tree.

Example


//from www  . ja  va 2 s.  c o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ProcessingInstruction;
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);

      addProcessingInstruction(doc);

    } catch (Exception e) {
      System.err.println(e);
    }
  }


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

}


<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>
       
   ]]>
</code>
<result><![CDATA[    
  <?xml version="1.0" standalone="yes"?>
<locations>
    <?validate phone="lookup"?>
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>




















Home »
  Java Tutorial »
    XML »




DOM
SAX