Incrementally Modify XML in Java
(For more code samples,
visit Official VTD-XML Blog)
(Separate code-only
VTD-XML tutorials are available in
C,
C++,
Java
and
C#)
This example application
shows you how to incrementally update XML documents using VTD-XML's
XMLModifier. The java code and the XML file are shown below:
ModifyXML.java
old.xml
The input and output XML are
shown below:
old.xml |
new.xml |
<document attr="">
<a> old content </a>
</document>
|
<document attr="value">
<b/>
<a> new content </a>
<c/>
</document>
|
The application logic goes into the following
code block:
import com.ximpleware.*;
import java.io.*;
public class ModifyXML {
public static void main(String[] s) throws Exception{
// Your application logic goes here
}
}
|
The application logic (along with comments)
is shown below:
VTDGen vg = new VTDGen(); //
Instantiate VTDGen
XMLModifier xm = new XMLModifier(); //Instantiate 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"));
}
|