A SOAP
Processor 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 shows how to process a
SOAP message using Java version of VTD-XML. The goal is to pull out all the
elements in the SOAP header that has the "mustUnderstand" attribute and write
the elements into a new file. The corresponding XML file and
Java files can be downloaded using the links below:
soap2.xml
SOAPProcessor.java
(Without XPath)
SOAPProcessor2.java
(Using XPath)
The following packages are
imported:
import
com.ximpleware.*;
import com.ximpleware.xpath.*;
import java.io.*; |
Open the input file(soap2.xml) and output
file(out.txt). Read the file content into a byte array
// open a file and read the content
into a byte array
// Modify this part of the code if the message is transmitted via HTTP
File f = new File("./soap2.xml");
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
fis.read(b);
// open file to output extracted fragments
File f1 = new File("./out.txt");
FileOutputStream fos = new FileOutputStream(f1); |
Instantiate an instance of VTDGen and pass to it the
byte buffer containing the input XML document. Then call the "parse(...)"
VTDGen vg = new VTDGen();
vg.setDoc(b);
vg.parse(true); // set namespace awareness
to true |
The following code snippet manually moves the cursor
to the sub-elements of the SOAP header and test for the attribute "mustUnderstand"
VTDNav vn = vg.getNav();
// get to the SOAP header
if (vn.toElementNS(VTDNav.FC,"http://www.w3.org/2003/05/soap-envelope","Header"))
{
if (vn.toElement(VTDNav.FC)) // to first child
{
do {
//
test for mustUnderstand
if (vn.hasAttrNS("http://www.w3.org/2003/05/soap-envelope","mustUnderstand")){
long l = vn.getElementFragment();
int len = (int) (l>>32);
int offset = (int) l;
fos.write(b, offset, len); //write the
fragment out into out.txt
fos.write("\n=========\n".getBytes());
}
}
while (vn.toElement(VTDNav.NS));
// navigate to next sibling
}
else
System.out.println("Header has not child elements");
}
else
System.out.println(" Dosesn't have a header"); |
Input and output file streams are closed at the end.
fis.close();
fos.close(); |
The following code snippet accomplishes essentially
the same task, except that it uses XPath and is shorter and simpler.
// instantiate the parser
VTDGen vg = new VTDGen();
vg.setDoc(b);
vg.parse(true); // set namespace awareness to
true
VTDNav vn = vg.getNav();
ap.setVTDNav(vn);
ap.declareXPathNameSpace("ns1","http://www.w3.org/2003/05/soap-envelope");
// Compile the XPath expression here
ap.selectXPath("/ns1:Envelope/ns1:Header/*[@ns1:mustUnderstand]");
System.out.println("expr string is " + ap.getExprString());
while(ap.evalXPath()!= -1){
long l =
vn.getElementFragment();
int len = (int) (l>>32);
int offset = (int) l;
fos.write(b, offset, len);
//write the fragment out into out.txt
fos.write("\n=========\n".getBytes());
}
fis.close();
fos.close(); |