DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jimmy has posted 14 posts at DZone. View Full User Profile

How To Incrementally Update XML Documents?

11.29.2009
| 4164 views |
  • submit to reddit
        
This example application shows you how to incrementally update XML documents using VTD-XML's XMLModifier.

import com.ximpleware.*;
import java.io.*;
// this file incrementally update an XML document
/* Input looks like this:
    	<document attr="">
    		 <a> old content </a>
    	</document>
 
 */

/* Output looks like this:
 
 		<document attr="value">
 		     <b/>
    		 <a> new content </a>
    	     <c/> 
    	<document>
  
 */
public class ModifyXML {    
    public static void main(String[] s) throws Exception{
        // instantiate VTDGen and XMLModifier
        VTDGen vg = new VTDGen();
        XMLModifier xm = new XMLModifier();
        if (vg.parseFile("old.xml",false)){
            VTDNav vn = vg.getNav();
            xm.bind(vn);
            
            // first update the value of attr
            int i = vn.getAttrVal("attr");
            if (i!=-1){
                xm.updateToken(i,"value");
            }
            
            // navigate to <a>
            if (vn.toElement(VTDNav.FC,"a")){
                // update the text content of <a>
                i=vn.getText();
                if (i!=-1){
                    xm.updateToken(i," new content ");
                }
                // insert an element before <a> (which is the cursor element)
                xm.insertBeforeElement("<b/>\n\t"); 
                
                // insert an element after <a> (which is the cursor element)
                xm.insertAfterElement("\n\t<c/>");  
            }
                        
            xm.output(new FileOutputStream("new.xml"));
        }        
    }
}