Tools and Technologies used in this article :

  1. w3c Dom parser

  2. JDK 1.6

  3. Eclipse 3.7

Download :

 

1. Create Java Project

Select from the menu File --> New --> Java Project (say 'HowToRetainXMLDocType').
Copy 'sampleXml.xml' and 'sc.dtd' directly under project directory.

File : sampleXml.xml
Note : We'll modify 'changefreq' of article having id '10' from 'weekly' to 'monthly', then save modified DOM to the same XML file.
File : sc.dtd
Note : We are going to use 'getElementById' method of Document to get the article having id '10'. So it is required to define 'id' attribute of element 'article' as type 'ID' in DTD file. Otherwise 'getElementById' will return null.

 

2. Write code

Create a java class (say com.srccodes.examples.howto.HowToRetainXMLDocType)
Modify the java class as per the following code.

File : HowToRetainXMLDocType.java

 

3. Overall Project Structure

Overall Project Structure

 

4. Run Your Code

Right click on 'HowToRetainXMLDocType.java' and select from context menu 'Run As' --> 'Java Application'.

Open the 'sampleXml.xml' and you will see that 'changefreq' of article having id '10' is modified to 'monthly' but DOCTYPE declaration part is missing.

File : sampleXml.xml

 

5. Add code to retain DOCTYPE declaration

Manually change the value of 'changefreq' from 'monthly' to 'weekly' for the article id 10 in 'sampleXml.xml'.
Modify 'saveToXml(Document xmlDoc, String filePath)' method as shown below

File : HowToRetainXMLDocType.java

 

6. Run Your Code Again

Right click on 'HowToRetainXMLDocType.java' and select from context menu 'Run As' --> 'Java Application'.

Open the 'sampleXml.xml' and you will see that 'changefreq' of article having id '10' is modified to 'monthly' and DOCTYPE declaration is also preserved in the xml file.

File : sampleXml.xml

 

Download Source Code

 

References