Search code examples
vtd-xml

VTD-XML creating an XML document


I am a bit confused on how to do this, all of the docs / examples show how to read and edit xml docs but there doesn't seem to be any clear way of creating an xml from scratch, I would rather not have to ship my program with a dummy xml file in order to edit one. any ideas? thanks.


Solution

  • What you could do instead would be to just hard-code an empty document like this:

    byte[] emptyDoc = "<?xml version='1.0' encoding='UTF-8'?><root></root>".getBytes("UTF-8");
    

    And then use that to create your VTDGen and XMLModifier, and start adding elements:

    VTDGen vg = new VTDGen();
    vg.setDoc(emptyDoc);
    vg.parse(true);
    
    VTDNav vn = vg.getNav();
    XMLModifier xm = new XMLModifier(vn);
    
    // Cursor is at root, update Root Element Name
    xm.updateElementName("employee");
    
    xm.insertAttribute(" id='6'");
    xm.insertAfterHead("<name>Bob Smith</name>");
    vn = xm.outputAndReparse();
    
    // etc...