We help IT Professionals succeed at work.

Adding a node to existing DOM using Xerces

acehbee
acehbee asked
on
I am writing a XML java code using Xerces and having problem with adding a new node.  The Xerces version
shouldn't be a matter, but I am using version 1.4.3 if anyoen want to know.  I get the XML document
using DOMParser and I always get the XML Not Modifiable error.

Here is how I got the Document:
-------------------------------------------
DOMParser parser = new DOMParser();
parser.parse(new InputSource(new FileInputStream("test.xml")));
Document doc = parser.getDocument();
-------------------------------------------

Let's say the XML is really simple xml
<person>
  <name>
     <last_name>doe</last_name>
     <first_name>john</first_name>
  </name>
  <title>CEO</title>
</person>

and I need to add <middle_initial>P</middle_initial>

Could anyone show me how to add the new node and then print in out using XML Serializer?

Here is the way i print out the XML (I copy this code from Xerces sample code):

-------------------------------------------------
OutputFormat format = new OutputFormat(doc);            StringWriter stringOut = new StringWriter();
           XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer();
serial.serialize( doc.getDocumentElement() );
--------------------------------------------------

Thanks
Comment
Watch Question

Independent Consultant
Commented:
acehbee,

This works with Xerces 1.4.2:

import java.io.*;
import org.apache.xerces.parsers.*;
import org.apache.xml.serialize.*;
import org.xml.sax.*;
import org.w3c.dom.*;

public class ReadAddWriteBack
{
     public static void main(String[] args)
     {
          try
          {
               DOMParser parser = new DOMParser();
               parser.parse(new InputSource(new FileInputStream("test.xml")));
               Document doc = parser.getDocument();
               
               Element person = doc.getDocumentElement();
               NodeList names = person.getElementsByTagName("name");
               Element name = (Element) names.item(0);
               
               Element middleInitial = doc.createElement("middle_inital");
               middleInitial.appendChild(doc.createTextNode("P"));
               name.appendChild(middleInitial);
               
               OutputFormat ofmt = new OutputFormat("xml", "UTF-8", true);
               
               FileOutputStream fout = new FileOutputStream("testout.xml");
               XMLSerializer ser = new XMLSerializer(fout, ofmt);
               ser.serialize(doc);
          }
          catch (Exception e)
          {
               e.printStackTrace();
          }
         
          System.exit(0);
     }
}

Regards,
WMB

Author

Commented:
Thanks.  That is what I am looking for.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.