Edit XML
content
(For more code samples,
visit Official VTD-XML Blog)
(Separate code-only
VTD-XML tutorials are available in
C,
C++,
Java
and
C#)
This application shows you
how to "fill in" text content of template XML documents (one with white
spaces text content intended to be overwritten). In this case, an XML
document becomes an empty form and your application just fills in the value.
The white spaces have to be wider than the new content, otherwise the
operation will not work. The implication is that now you can generate those
XML document templates and use VTD-XML as a form "filler" to dramatically
speed up the serialization performance.
The files for this example
are listed below:
old.xml
new.xml
overWrite.java
The input and output of the
application looks like this:
Input |
Output |
<root>
<a> some content </a>
<b>
</b>
<c>
</c>
</root> |
<root>
<a> 123
</a>
<b> 234
</b>
<c>new content </c>
</root> |
The application logic goes
into the following code block.
import com.ximpleware.*;
import java.io.*;
public class overWrite {
public static void main(String[] args)
throws Exception {
// logic goes here
}
}
|
The application logic
basically visits individual element a, b and c, then calls "overWrite(...)"
to fill in new content. The function "overWrite(...)" returns true if
successful. Otherwise, it returns false, indicating the length of the token
(to be overwritten) is not wide enough to hold the new content. The other
thing worth noting: if "overWrite" is successful, it will completely
replace the byte content of the token with new content and white spaces.
VTDGen vg = new VTDGen();
if (vg.parseFile("old.xml",false)){
VTDNav vn =
vg.getNav();
if (vn.toElement(VTDNav.FIRST_CHILD)){
// cursor at <a>
int i = vn.getText();
if (vn.overWrite(i," 123".getBytes())==false){
System.out.println("overWrite at "+i+" failed");
}
// cursor at <b>
vn.toElement(VTDNav.NEXT_SIBLING);
i = vn.getText();
if (vn.overWrite(i," 234".getBytes())==false){
System.out.println("overWrite at "+i+" failed");
}
// cursor at <c>
vn.toElement(VTDNav.NEXT_SIBLING);
i = vn.getText();
if (vn.overWrite(i,"new content".getBytes())==false){
System.out.println("overWrite at "+i+" failed");
}
// get the byte array of overwritten XML
byte[] ba = vn.getXML().getBytes();
FileOutputStream fos = new FileOutputStream("new.xml");
fos.write(ba);
}
}
|