XML string from Java
Hi
I have requirement in which i have a jsp that i use to get information from users. I need to convert the info to XML data into a String , whihc i later use to pass as messages using AQ.
I also have to, at a later point retreive the data from the XML String, update some information and recreate the XML string object with the new data.
I do not want to use the XML SQL Utility as this could provide too costly in terms of database hits .
Is there some XML Parser methods i can use to do the generation and retrieval of XML data into Strings.
Thanks
null
Sort of hack but the way I did it was
Convert to String:
Construct a ByteArrayOutputStream
print your documenet to this,
and then call the toString() on the
ByteArrayOutputStream.
Convert from String to an XMLDocument:
Construct a StringReader(String s)
Construct a DOMParser and parse the
StringReader.
Hope this helps.
null
Similar Messages
-
Sending long XML strings from a servlet
Hi,
I'm trying to send a long (16K) XML string from a Java servlet to a
MSXML2.XMLHTTP40 client. The client doesn't receive any data when the
string is longer than about 2K .
I am using the POST method.
I have tried increasing the buffer size on the sending side with
HttpServletResponse.setBufferSize() - this had no effect.
Any ideas ?
Thanks very much for your help,
RodLooks like the problem is on the client side (MSXML) because I can flawlessly send half-megs XML files from a Servlet to a browser or a java.net.URL
-
Generation of xml file from java code
hi,
I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html -
How to edit the existing data in the XML file from java programming.
Hi all
i am able to create XML file with the sample data as below from java programming.
i need sample code on how to edit the existing data in the XML file?
for example
<?xml version="1.0"?>
<mydata>
<data1>
<key1>467</key1>
<name1>Paul</name1>
<id1>123</id1>
</data1>
<data2>
<key2>467</key2>
<name2>Paul</name2>
<id2>123</id2>
</data2>
</mydata>
i am able to insert the data in the XML.
now i need sample code on how to modify the data in the above XML file from the java programming for only key2,name2,id2 tags only. the remaining tags data in the XML file i want to keep same data except for key2,name2,id2 which are i want to modify from java code
Regards
Sunil
[points will be always rewardable]hi
u need a parser or validate the xml file for to read the xml file from java coding u need for this
xml4j.jar u can download this file from here
http://www.alphaworks.ibm.com/tech/xml4j
or we can use the SAX(simple API for XML)
some sample applications for this
http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
http://www.developertutorials.com/tutorials/java/read-xml-file-in-java-050611/page1.html
http://www.xml-training-guide.com/e-xml44.html
let me know u need any other info
bvr -
How I can create a XML file from java Aplication
How I can create a XML file from java Aplication
whith have a the following structure
<users>
<user>
<login>anyName</login>
<password>xxxx</password>
</user>
</users>
the password label must be encripted
accept any suggestionLet us assume you have all the data from the jsp form in an java bean object..
Now you want a xml file. This can be acheived in 2 ways
1. Write it into a file using java.io classes. Say you have a class with name
write("<name>"+obj.getName+</name>);
bingo you have a flat file with the xml
2. Use data binding to do the trick
will recommend JiBx and Castor for the 2nd option
Regards,
Rajagopal -
Creating XML file from Java Bean
Hi
Are there any standard methods in Java 1.5 to create XML file from java bean,
i can use JAXB or castor to do so,
But i would like to know if there is any thing in java core classes,
I have seen XMLEncoder, but this is not what i want.
Any ideas
AshishMarshall JavaBean to an XML document with JAXB or XMLBeans.
-
How to modify an existing xml file from java code.
Hi
I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
For example if xml file(studlist.xml) is as below:
<?xml version="1.0" encoding="UTF-8"?>
<StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
<Student>
<Name>ram</Name>
<Age>27</Age>
</Student>
<Student>
<Name>sham</Name>
<Age>26</Age>
</Student>
</StudentList>
Now suppose i have set name to victor using student.setName,
and set age to 20 using setAge from javacode,
the new xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
<Student>
<Name>ram</Name>
<Age>27</Age>
</Student>
<Student>
<Name>sham</Name>
<Age>26</Age>
</Student>
</StudentList>
<Student>
<Name>victor</Name>
<Age>20</Age>
</Student>
As observed this is not a valid xml file.But how can i modify without any errors?I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
// gets the root element of the specified file (code not shown)
Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
// write a new student element
Element student = document.createElement("Student"); // creates the new student
rootElement.appendChild(student); // ***appends it to the root element***
Element name = document.createElement("Name"); // creates the name element
name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
student.appendChild(name); // appends the name to the student
Element age= document.createElement("Age"); // creates the age element
age.appendChild(document.createTextNode("26")); // adds the age text to the age element
student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM -
How to create XML string from BPM Business Object?
Hello,
I have a business object in my BPM project and I need to transform it in a XML string:
From:
Business Object: Customer
Properties: Name, Age
To:
"<Customer><Name>Robert</Name><Age>17</Age></Customer>"
How can I do this?
Thanks.Hello,
I have a business object in my BPM project and I need to transform it in a XML string:
From:
Business Object: Customer
Properties: Name, Age
To:
"<Customer><Name>Robert</Name><Age>17</Age></Customer>"
How can I do this?
Thanks. -
Passing a String from Java to Javascript
Does anybody know how to pass a string from Java class to Javascript ? Can it be done?
If you are talking in terms of web terminology...
People do intialization of page in the following way.
var java_script_variable = <%=String_variable%> -
How to get an XML string from a Java Bean without wrting to a file first ?
I know we can save a Java Bean to an XML file with XMLEncoder and then read it back with XMLDecoder.
But how can I get an XML string of a Java Bean without writing to a file first ?
For instance :
My_Class A_Class = new My_Class("a",1,2,"Z", ...);
String XML_String_Of_The_Class = an XML representation of A_Class ?
Of course I can save it to a file with XMLEncoder, and read it in using XMLDecoder, then delete the file, I wonder if it is possible to skip all that and get the XML string directly ?
FrankI think so too, but I am trying to send the object to a servlet as shown below, since I don't know how to send an object to a servlet, I can only turn it into a string and reconstruct it back to an object on the server side after receiving it :
import java.io.*;
import java.net.*;
import java.util.*;
class Servlet_Message // Send a message to an HTTP servlet. The protocol is a GET or POST request with a URLEncoded string holding the arguments sent as name=value pairs.
public static int GET=0;
public static int POST=1;
private URL servlet;
// the URL of the servlet to send messages to
public Servlet_Message(URL servlet) { this.servlet=servlet; }
public String sendMessage(Properties args) throws IOException { return sendMessage(args,POST); }
// Send the request. Return the input stream with the response if the request succeeds.
// @param args the arguments to send to the servlet
// @param method GET or POST
// @exception IOException if error sending request
// @return the response from the servlet to this message
public String sendMessage(Properties args,int method) throws IOException
String Input_Line;
StringBuffer Result_Buf=new StringBuffer();
// Set this up any way you want -- POST can be used for all calls, but request headers
// cannot be set in JDK 1.0.2 so the query string still must be used to pass arguments.
if (method==GET)
URL url=new URL(servlet.toExternalForm()+"?"+toEncodedString(args));
BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
else
URLConnection conn=servlet.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
// Work around a Netscape bug
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// POST the request data (html form encoded)
DataOutputStream out=new DataOutputStream(conn.getOutputStream());
if (args!=null && args.size()>0)
out.writeBytes(toEncodedString(args));
// System.out.println("ServletMessage args: "+args);
// System.out.println("ServletMessage toEncString args: "+toEncodedString(args));
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
out.flush();
out.close(); // ESSENTIAL for this to work!
return Result_Buf.toString(); // Read the POST response data
// Encode the arguments in the property set as a URL-encoded string. Multiple name=value pairs are separated by ampersands.
// @return the URLEncoded string with name=value pairs
public String toEncodedString(Properties args)
StringBuffer sb=new StringBuffer();
if (args!=null)
String sep="";
Enumeration names=args.propertyNames();
while (names.hasMoreElements())
String name=(String)names.nextElement();
try { sb.append(sep+URLEncoder.encode(name,"UTF-8")+"="+URLEncoder.encode(args.getProperty(name),"UTF-8")); }
// try { sb.append(sep+URLEncoder.encode(name,"UTF-16")+"="+URLEncoder.encode(args.getProperty(name),"UTF-16")); }
catch (UnsupportedEncodingException e) { System.out.println(e); }
sep="&";
return sb.toString();
}As shown above the servlet need to encode a string.
Now my question becomes :
<1> Is it possible to send an object to a servlet, if so how ? And at the receiving end how to get it back to an object ?
<2> If it can't be done, how can I be sure to encode the string in the right format to send it over to the servlet ?
Frank -
How to Generate XML File from Java Code.
I want to generate the xml file from the java code.
Could you plz suggest any webSite address with example?Here is the code
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXML {
private DocumentBuilderFactory factory = null;
private DocumentBuilder builder = null;
private Document document = null;
public CreateXML() {
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
document = builder.newDocument();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
/** Creates the document for xml. */
public Document createDocument(){
try{
Element root = document.createElement("Root");
Element child = document.createElement("child");
root.appendChild(child);
document.appendChild(root);
}catch(RuntimeException e){
e.printStackTrace();
return document;
/** Saves the document as xml. */
public void saveDocument(Document document){
try{
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult stream = new StreamResult(new File("sample.xml"));
transformer.transform(source, stream);
System.out.println("XML Created !!");
}catch(TransformerConfigurationException e){
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
public static void main(String args[]){
CreateXML createXML = new CreateXML();
Document document = createXML.createDocument();
createXML.saveDocument(document);
} -
Convert XML-String from Codepage utf-16 to ISO-8859-1
Hi to all experts,
our system is now unicode with codepage 4102 (UTF-16) and we do an Simple Transformation for creating an XML-String.
before UniCode : xml_data = <?xml version="1.0" encoding="iso-8859-1"?>#<transactionRequest userID=" .......
now with UniCode : xml_data = <?xml version="1.0" encoding="utf-16"?>#<transactionRequest userID=".......
The xml_data transfered to an external Sytem via HTTPS- Communication direct from ABAP.
The external Sytem send an Error Request:
<?xml version="1.0" encoding="ISO-8859-1"?>#<transactionResponse># <transactionErrorResponse># <errorResponse># <errorCode>SYS-0001</errorCode># <errorDescription>java.lang.Exception: null[ #<?xml version="1.................
Have you any idea
Thanks for your help!
Peter
Edited by: Peter Pforr on Sep 25, 2008 9:59 AM
Edited by: Peter Pforr on Sep 25, 2008 10:14 AMDarshan,
Did you get an answer for this question? We have same requirement to create XML file in ISO-8859-1 format with Attributes is set to "Y" and CDATA is being used for data.
Can you please let me know if you still remember how did you achieve it?
Satyen... -
Why returning string from java stored function failed ? HELP ME, PLEASE
Hi everybody,
I created java stored function: it's doing http post, parsing xml from http reply, and returning string result.
Sometimes, it doesn't return any value. What can be a reason ?
The high level procedure, has following form:
class SBE {
public static String call(String arg0) {
SBE sbe=new SBE("d:\\oracle\\ora81\\network\\log\\SBE.log");
String result=SBEParser.go(sbe.sendRequest(arg0, ""), sbe.logger);
sbe.logger.log(result);
sbe.logger.log("Finish SBE intetraction");
return result;
PLSQL wrapper has a simple form:
create or replace package PG_SBE as
function CALL(arg0 in varchar2) return varchar2;
end;
create or replace package body PG_SBE as
function CALL(arg0 varchar2) return varchar2 as language java name 'SBE.call(java.lang.String) return java.lang.String';
end;
In log file ("d:\\oracle\\ora81\\network\\log\\SBE.log"), I can find message :
"Finish SBE intetraction"
but query:
select pg_sbe.call("any argument") from dual;
doesn't finish.
What can be a reason ? What can I do to trace stage of convertion java string to varchar ?
Please help me...
Best regards
Marek<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Stefan Fdgersten ([email protected]):
Maybe your call is wrong... Shouldn't there be a "?" instead of "1"?
Your code:
String myquery = "begin :1 := jspTest; end;";
I provide my (working) call from java as an example. Maybe it is of any help... :)
import java.sql.*;
import oracle.jdbc.driver.*;
public Vector getAllHosts() throws SQLException {
//return getHosts(false, -1);
Connection conn = null;
CallableStatement cs = null;
Vector hostV = new Vector();
try {
conn = getConnection();
String query = "{ ? = call curTestPkg.curTestFunc}";
cs = conn.prepareCall(query);
cs.registerOutParameter(1, OracleTypes.CURSOR);
cs.execute();
ResultSet rs = ((OracleCallableStatement)cs).getCursor(1);
while (rs.next()) {
Host host = new Host(
rs.getInt("hostid")
, rs.getString("name")
, rs.getString("descr")
, rs.getString("os"));
hostV.add(host);
cs.close();
return hostV;
} finally {
close(conn, cs);
<HR></BLOCKQUOTE>
hi Stefan thanx.....even after changing the call statement i get the same error. i changed query string as...
String myquery = "{ ? = call jspTest}";
CallableStatement cst = con.prepareCall(myquery);
Can u please check out my call sepc that i have written in pl/sql and plz let me know it there is any error in that.
PS : THIS IS THE FIRST TIME I AM WORKING WITH PL/SQL AND IT IS URGENT -
Why returning string from java stored function failed ?
I created java stored function: it's doing http post, parsing xml from http reply, and returning string result.
Sometimes, it doesn't return any value. What can be a reason ?
The high level procedure, has following form:
class SBE {
public static String call(String arg0) {
SBE sbe=new SBE("d:\\oracle\\ora81\\network\\log\\SBE.log");
String result=SBEParser.go(sbe.sendRequest(arg0, ""), sbe.logger);
sbe.logger.log(result);
sbe.logger.log("Finish SBE intetraction");
return result;
PLSQL wrapper has a simple form:
create or replace package PG_SBE as
function CALL(arg0 in varchar2) return varchar2;
end;
create or replace package body PG_SBE as
function CALL(arg0 varchar2) return varchar2 as language java name 'SBE.call(java.lang.String) return java.lang.String';
end;
In log file ("d:\\oracle\\ora81\\network\\log\\SBE.log"), I can find message :
"Finish SBE intetraction"
but query:
select pg_sbe.call("any argument") from dual;
doesn't finish.
What can be a reason ? What can I do to trace stage of convertion java string to varchar ?
Please help me...
MarekThis comes up periodically. It just isn't possible using that type of approach. Probably the best you could do is the create an ADT (containing collections) and use that to pass a 'batch' of information.
Hopefully this will get addressed in the next release of the database. -
Reg XML generation from java objects using SAX 2.0
i'm using java 1.6 and i've imported following class to generate XML from java objects
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
the following class has been imple her to create a Xml file and tag elements ,
OutputFormat of = new OutputFormat("XML", "iso-8859-1", true);
XMLSerializer serializer = new XMLSerializer(fos, of);
ContentHandler hd = serializer.asContentHandler();
hd.startDocument();
everything works fine but i'm getting warrnin reg the serializer and outputformat
warring is:
com.sun.org.apache.xml.internal.serialize.OutputFormat is Sun proprietary API and may be removed in a future release
com.sun.org.apache.xml.internal.serialize.OutputFormat is Sun proprietary API and may be removed in a future release
HOW CAN I AVOID DS WARRING PLZ HELP REG DS
thanks ,
with regards,
Rajesh.SI've been having the same problem. Here is what i found:
[http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6476630]
Hope that helps (or at least helps you feel better).
Maybe you are looking for
-
Since the last firefox upgrade my copy/paste and adobe doc viewer functionality is gone. == This happened == Every time Firefox opened == last upgrade
-
I have come back to BT recently after having had a lot of trouble with my previous ISPs connection speeds when trying to use HD TV services. I have option 3 "unlimited" and was assured when returning to BT that using such services as iplayer,sky play
-
Where do i find my code number to instal indesign on a second computer? or a new computer
where do i find my code number to instal indesign on a second computer? or a new computer !
-
I have Photshop CS6 Extended but when I click on the .cr2 which is the RAW file I keep getting an error message "Could not complete your request because it is not the right kind of document" Any suggestions? I have tried installing the camera raw plu
-
Fonts appears odd, like "out of focus"
Hi, I have installed FF Beta 4.0 10 in my job PC and in my Vaio laptop with high resolution screen. In the PC doesn't look as before and neither as Chrome looks (sorry...). But in the Vaio looks absolute bad, specially menus, they are not well define