In order to transmit complex data during WebServices, we often use strings in XML format for transmission. This is mainly because XML has the advantages of data access, cross-platform and cross-language access. See the following example:
Public String getallnewspace (){
Stringbuffer toclient = new stringbuffer ("<root> ");
..............................
If (null! = Dataset ){
While (Dataset. Next ()){
Toclient. append ("<user> ");
Toclient. append ("<username>"); // <! [CDATA [
Toclient. append (Dataset. getstring (1 ));
Toclient. append ("</username>"); //]
Toclient. append ("<userid> ");
Toclient. append (Dataset. getstring (2 ));
Toclient. append ("</userid> ");
Toclient. append ("</user> ");
}
}
Toclient. append ("</root> ");
Return toclient. tostring ();
}
If the <username> node contains characters such as "&", "<", and ">", an error occurs while interpreting the XML.
There are two solutions:
1. Get an XML string from the XML Document Object and return it to the client. xmldocument cannot be directly returned to the client because the XML Document Object in Java cannot be correctly interpreted by other languages, we can only return XML strings:
Public String getallnewspace (){
Document document = incluenthelper. createdocument ();
Element root = Document. addelement ("root ");
..............................
If (null! = Dataset ){
While (Dataset. Next ()){
Element user = root. addelement ("user ");
Element username = user. addelement ("username ");
Username. settext (Dataset. getstring (1 ));
Element userid = user. addelement ("userid ");
Userid. settext (Dataset. getstring (2 ));
}
}
Return document. asxml ();
}
2. Add DTD verification to the XML string: Add "<! [CDATA []"
Public String getallnewspace (){
Stringbuffer toclient = new stringbuffer ("<root> ");
..............................
If (null! = Dataset ){
While (Dataset. Next ()){
Toclient. append ("<user> ");
Toclient. append ("<username> <! [CDATA [");
Toclient. append (Dataset. getstring (1 ));
Toclient. append ("] </username> ");
Toclient. append ("<userid> ");
Toclient. append (Dataset. getstring (2 ));
Toclient. append ("</userid> ");
Toclient. append ("</user> ");
}
}
Toclient. append ("</root> ");
Return toclient. tostring ();
}