Sending Custom Java Objects over XML!!
Hello all !
Can anybody please tell me how can I send custom Java Objects through XML? For example we can set attributes for a node using the setAttribute method, it accepts only strings, also the setTextContent method requires text and sets the node's value.Can I some way set my own Java object as the value of a particular node or attach it to the node?
Thanks in advance.
Kami_Pakistan wrote:
So I should rather go for Marshalling or Serialization or is there any other work-around possible?I don't know. You didn't say what you had against text formats. Since all Java objects are composed of primitives when you get right down to the bottom, everything in Java can be serialized as text versions of those primitives. So you're going to have to explain why you think a work-around is necessary at all.
Similar Messages
-
Calling Web Service Proxy with Custom java Object as parameter
I created a web service proxy from WSDL URL using JDeveloper 11g(.5 version)
I need to call a webservice method which takes custom Java Object( Ex: ABC.java) as Input parameter. It creates the XSD java (ABC.java) file for that.
@XmlElementRef(name = "abc", namespace = "http://impl.service.ns.test", type = JAXBElement.class)
protected JAXBElement<ABC> abc;
ABC.java has a property of type java.util.Set of a custom Java Object (Set<XYZ.class>)
It doesn't create xsd file for XYZ.java.
@XmlElementRef(name = "XYZ", namespace = "http://model.ns.test/xsd", type = JAXBElement.class)
protected JAXBElement<Set> xyz;
Please help me.The passing of Java objects in and out of a web service is NOT supported. variables must be xml documents defined by a XML schema. In my opinion, missing Java object and WSDL is not a good idea. -Edwin
-
How can I use XStream to persist complicated Java Object to XML & backward
Dear Sir:
I met a problem as demo in my code below when i use XTream to persist my Java Object;
How can I use XStream to persist complicated Java Object to XML & backward??
See
[1] main code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class PhoneList {
ArrayList<PhoneNumber> phones;
ArrayList<Person> person;
private PhoneList myphonelist ;
private LocationTest location;
private PhoneList(String name) {
phones = new ArrayList<PhoneNumber>();
person = new ArrayList<Person>();
public ArrayList<PhoneNumber> getphones() {
return phones;
public ArrayList<Person> getperson() {
return person;
public void addPhoneNumber(PhoneNumber b1) {
this.phones.add(b1);
public void removePhoneNumber(PhoneNumber b1) {
this.phones.remove(b1);
public void addPerson(Person p1) {
this.person.add(p1);
public void removePerson(Person p1) {
this.person.remove(p1);
public void BuildList(){
location = new LocationTest();
XStream xstream = new XStream();
myphonelist = new PhoneList("PhoneList");
Person joe = new Person("Joe, Wallace");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
Person geo= new Person("George Nixson");
geo.setPhone(new PhoneNumber(925, "228-9999"));
geo.getPhone().setLocationTest(location);
myphonelist.addPerson(joe);
myphonelist.addPerson(geo);
public PhoneList(){
XStream xstream = new XStream();
BuildList();
saveStringToFile("C:\\temp\\test\\PhoneList.xml",convertToXML(myphonelist));
public void saveStringToFile(String fileName, String saveString) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(
new FileWriter(fileName));
try {
bw.write(saveString);
finally {
bw.close();
catch (IOException ex) {
ex.printStackTrace();
//return saved;
public String getStringFromFile(String fileName) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(fileName));
try {
String s;
while ((s = br.readLine()) != null) {
// add linefeed (\n) back since stripped by readline()
sb.append(s + "\n");
finally {
br.close();
catch (Exception ex) {
ex.printStackTrace();
return sb.toString();
public String convertToXML(PhoneList phonelist) {
XStream xstream = new XStream(new DomDriver());
xstream.setMode(xstream.ID_REFERENCES) ;
return xstream.toXML(phonelist);
public static void main(String[] args) {
new PhoneList();
}[2].
import java.io.Serializable;
import javax.swing.JFrame;
public class PhoneNumber implements Serializable{
private String phone;
private String fax;
private int code;
private String number;
private String address;
private String school;
private LocationTest location;
public PhoneNumber(int i, String str) {
setCode(i);
setNumber(str);
address = "4256, Washington DC, USA";
school = "Washington State University";
public Object getPerson() {
return null;
public void setPhone(String phone) {
this.phone = phone;
public String getPhone() {
return phone;
public void setFax(String fax) {
this.fax = fax;
public String getFax() {
return fax;
public void setCode(int code) {
this.code = code;
public int getCode() {
return code;
public void setNumber(String number) {
this.number = number;
public String getNumber() {
return number;
public void setLocationTest(LocationTest bd) {
this.location = bd;
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(location);
f.getContentPane().add(location.getControls(), "Last");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
public LocationTest getLocationTest() {
return location;
}[3].
package test.temp;
import java.io.Serializable;
public class Person implements Serializable{
private String fullname;
@SuppressWarnings("unused")
private PhoneNumber phone;
@SuppressWarnings("unused")
private PhoneNumber fax;
public Person(){
public Person(String fname){
fullname=fname;
public void setPhone(PhoneNumber phoneNumber) {
phone = phoneNumber;
public void setFax(PhoneNumber phoneNumber) {
fax = phoneNumber;
public PhoneNumber getPhone() {
return phone ;
public PhoneNumber getFax() {
return fax;
public String getName() {
return fullname ;
public void setName(String name) {
this.fullname = name;
public String toString() {
return getName();
}[4]. LocationTest.java
package test.temp;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class LocationTest extends JPanel implements ChangeListener
Ellipse2D.Double ball;
Line2D.Double line;
JSlider translate;
double lastTheta = 0;
public void stateChanged(ChangeEvent e)
JSlider slider = (JSlider)e.getSource();
String name = slider.getName();
int value = slider.getValue();
if(name.equals("rotation"))
tilt(Math.toRadians(value));
else if(name.equals("translate"))
moveBall(value);
repaint();
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(ball == null)
initGeom();
g2.setPaint(Color.green.darker());
g2.draw(line);
g2.setPaint(Color.red);
g2.fill(ball);
private void initGeom()
int w = getWidth();
int h = getHeight();
int DIA = 30;
int padFromEnd = 5;
line = new Line2D.Double(w/4, h*15/16, w*3/4, h*15/16);
double x = line.x2 - padFromEnd - DIA;
double y = line.y2 - DIA;
ball = new Ellipse2D.Double(x, y, DIA, DIA);
// update translate slider values
int max = (int)line.getP1().distance(line.getP2());
translate.setMaximum(max);
translate.setValue(max-padFromEnd);
private void tilt(double theta)
// rotate line from left end
Point2D pivot = line.getP1();
double lineLength = pivot.distance(line.getP2());
Point2D.Double p2 = new Point2D.Double();
p2.x = pivot.getX() + lineLength*Math.cos(theta);
p2.y = pivot.getY() + lineLength*Math.sin(theta);
line.setLine(pivot, p2);
// find angle from pivot to ball center relative to line
// ie, ball center -> pivot -> line end
double cx = ball.getCenterX();
double cy = ball.getCenterY();
double pivotToCenter = pivot.distance(cx, cy);
// angle of ball to horizon
double dy = cy - pivot.getY();
double dx = cx - pivot.getX();
// relative angle phi = ball_to_horizon - last line_to_horizon
double phi = Math.atan2(dy, dx) - lastTheta;
// rotate ball from pivot
double x = pivot.getX() + pivotToCenter*Math.cos(theta+phi);
double y = pivot.getY() + pivotToCenter*Math.sin(theta+phi);
ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
lastTheta = theta; // save theta for next time
private void moveBall(int distance)
Point2D pivot = line.getP1();
// ball touches line at distance from pivot
double contactX = pivot.getX() + distance*Math.cos(lastTheta);
double contactY = pivot.getY() + distance*Math.sin(lastTheta);
// find new center location of ball
// angle lambda = lastTheta - 90 degrees (anti-clockwise)
double lambda = lastTheta - Math.PI/2;
double x = contactX + (ball.width/2)*Math.cos(lambda);
double y = contactY + (ball.height/2)*Math.sin(lambda);
ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
JPanel getControls()
JSlider rotate = getSlider("rotation angle", "rotation", -90, 0, 0, 5, 15);
translate = getSlider("distance from end", "translate", 0, 100, 100,25, 50);
JPanel panel = new JPanel(new GridLayout(0,1));
panel.add(rotate);
panel.add(translate);
return panel;
private JSlider getSlider(String title, String name, int min, int max,
int value, int minorSpace, int majorSpace)
JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, value);
slider.setBorder(BorderFactory.createTitledBorder(title));
slider.setName(name);
slider.setPaintTicks(true);
slider.setMinorTickSpacing(minorSpace);
slider.setMajorTickSpacing(majorSpace);
slider.setPaintLabels(true);
slider.addChangeListener(this);
return slider;
}OK, My questions are:
[1]. what I generated XML by XSTream is very complicated, especially for object LocationTest, Can we make it as simple as others such as Person object??
[2]. after I run it, LocationTest will popup and a red ball in a panel will dsiplay, after I change red ball's position, I hope to persist it to xml, then when I read it back, I hope to get same picture, ie, red ball stiil in old position, How to do that??
Thanks a lot!!Positive feedback? Then please take this in a positive way: if you want to work on persisting Java objects into XML, then GUI programming is irrelevant to that goal. The 1,000 lines of code you posted there appeared to me to have a whole lot of GUI code in it. You should produce a smaller (much smaller) example of what you want to do. Calling the working code from your GUI program should come later.
-
Serializing Java Objects to XML files
Hi,
We looking for SAP library which can serialize Java Objects into XML files.
Can you point us were to find it ?
We have found such open source library called "XStream" at the following link
http://www.xml.com/pub/a/2004/08/18/xstream.html
Is it allowed to use that library inside SAP released software ?
Thanks
OritHow about https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/webcontent/uuid/83f6d2fb-0c01-0010-a2ba-a2ec94ba08f4 [original link is broken] [original link is broken]? Depends on your use cases...
Both are supported in SAP NW CE 7.1.
HTH!
-- Vladimir -
Java objects to xml streams in pipe
hi all
I am stuck up at a point in my project.I want to write and read a java object ie Record record , in to a pipe.Not the record object has the data that i reads from a text file.I want the data written in the pipe in the from of xml stream and that read from the pipe in the xml stream .can anyone suggest me with some concerete solution
thanking you
yashXMLBeans and JAXB technologies convert Java Objects to XML.
-
How to convert Java Objects into xml?
Hello Java Gurus
how to convert Java Objects into xml? i heard xstream can be use for that but i am looking something which is good in performance.
really need your help guys.
thanks in advance.There are apparently a variety of Java/XML bindings. Try Google.
And don't be so demanding. -
Design pattern for converting multiple complex Java objects to XML
What is the traditionally accepted high performance mechanism for converting Java objects to XML? Some options I have explored are:
1. SAX-JAXP
2. DOM-JAXP
3. JAXB
4. Castor
Which of these usually performs the best for large, complex objects which contain multiple subobjects?
Thanks.Take a look at XStream. It will simplify your life considerably.
Typical code snipped
XStream xStream = new XStream();
xStream.toXML(someJavaObject);That's it. Regarding the others...
1. SAX-JAXP
Can be used for XML -> Java Objects, but you have to write significant amounts of ugly, high maintainenance code
2. DOM-JAXP
Slower and more memory intensive than SAX because you need to read the whole object into memory first. Just as ugly and high maintenance.
3. JAXB
Actually very good for going from a POJO to XML, but rubbish in the opposite direction. The worst part is it adds an extra step to your build process as you need to tell it to generate and compile the source for doing this.
4. Castor
Not used it since JAXB came out. Works pretty much in the same way but also supports XML -> POJOs. -
Using Custom Java Class - WorkflowRegistry.xml
I am using a custom java class in workflow. While executing I am getting errot -
com.waveset.util.WavesetException: Class com.LdapGroupMod is not a WorkflowApplication
It seems from documentation that I need to add this in workflowregistry.xml file. I added the same like given below -
<WorkflowApplication name='Workflow Name'
class='com.LdapGroupMod'>
<Comments>Nothing Here</Comments>
</WorkflowApplication>Even tried restaring the application server but I am still getting same error. Any idea what needs to be done here? or I am missing smething?Well the first thing would be to read the workflowRegistry.xml file. The header talks about internal and external applications and so on. The crucial part is that any application registered must implement the WorkflowApplication interface (which I guess your class dont do)
I gave up. I am totally baffled by the documentation. I admit it.
What I did was to create an Script action in an Activity where the script used Xpress to invoke my class. It seems to work. -
I want to create a tree structure for java object. These java objects are populated after the parsing the xml. But what could be the logic for adding child to parent when there are
many sub nodes? I wanted to use one recursive function which iterate through all the elements of the xml file. But I have not got the idea how to add one child object to parent object.
following are my classes. Any help on this highly appreciated.
public class TreeObject {
private String name;
private TreeParent parent;
public TreeObject(String name) {
this.name = name;
public String getName() {
return name;
public void setParent(TreeParent parent) {
this.parent = parent;
public TreeParent getParent() {
return parent;
public String toString() {
return getName();
import java.util.ArrayList;
public class TreeParent extends TreeObject {
private TreeObject treeObject ;
private ArrayList children;
public TreeParent(String name) {
super(name);
children = new ArrayList();
public void addChild(TreeObject child) {
children.add(child);
child.setParent(this);
treeObject = child ;
public void removeChild(TreeObject child) {
children.remove(child);
child.setParent(null);
public TreeObject [] getChildren() {
return (TreeObject [])children.toArray(new TreeObject[children.size()]);
public boolean hasChildren() {
return children.size()>0;
public TreeObject getChild(){
return treeObject;
private TreeParent getChilderen(Element rootNode){
List list = rootNode.getChildren();
String rootNodeName = rootNode.getName();
TreeParent root = new TreeParent(rootNodeName);
for (int i=0; i< list.size(); i++)
Element node = (Element) list.get(i);
if(node.getChildren().size() > 0){
// TreeParent treeParent = new TreeParent(node.getText());
TreeParent treesub = new TreeParent(node.getText());
treesub.addChild(treesub);
//TreeParent p = treeParent.getParent();
// rootParent.addChild(treeParent);
}else{
TreeObject object = new TreeObject(node.getText());
root.addChild(object);
getChilderen(node);
return root ;
public TreeParent buildTree(String filePath) {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(filePath);
try{
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
// List list = rootNode.getChildren("staff");
TreeParent rootParent = getChilderen(rootNode);
return rootParent ;
}catch(IOException io){
System.out.println(io.getMessage());
}catch(JDOMException jdomex){
System.out.println(jdomex.getMessage());
return null;
Edited by: 870611 on Jul 6, 2011 6:27 AMHi
I recommend you use the API JAXB. Is much simpler.
here a link: http://www.oracle.com/technetwork/articles/javase/index-140168.html
here a example: http://download.oracle.com/javaee/5/tutorial/doc/bnbay.html#bnbbc -
API for converting a Java object into XML?
Do you know of any Java API that I could use to convert a Java
object into its equivalent XML representation?
For example if I have a class called "Foo" with variables va, vb
and I have an instance of Foo with va having the value 1 and vb
having the value 2, I would like be able to generate the
following XML fragment:
<Foo>
<va>1</va>
<vb>2</vb>
</Foo>
Thanks,
-- Rob
nullRob Tan (guest) wrote:
: Do you know of any Java API that I could use to convert a Java
: object into its equivalent XML representation?
: For example if I have a class called "Foo" with variables va,
vb
: and I have an instance of Foo with va having the value 1 and
vb
: having the value 2, I would like be able to generate the
: following XML fragment:
: <Foo>
: <va>1</va>
: <vb>2</vb>
: </Foo>
: Thanks,
: -- Rob
There is none that I know of.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
null -
JAXB - Marshalling populated Java object into XML
I have a populated Java object that I'd like to marshall to an xml file.
I don't instantiate this object from a DTD, nor do I need to generate the object via unmarshalling an xml. I'm just trying to build something akin to a toXML() method for this object.
Is JAXB what I should be using?
Any suggestions?
Thanks a lot.
PaulHi Paul,
Did you ever sort this out?
I too am now having problems with Marshalling to and from XML.
I have been able to write my own Marshalling class but can't seem to be able to DeMarshal a XML stream to a SOAP object.
Please reply to this message if you are able to maybe shed some light on my problem.
I have a populated Java object that I'd like to
marshall to an xml file.
I don't instantiate this object from a DTD, nor do I
need to generate the object via unmarshalling an xml.
I'm just trying to build something akin to a toXML()
method for this object.
Is JAXB what I should be using?
Any suggestions?
Thanks a lot.
Paul -
USing Jdeveloper 11.1.1.0.2+ADF
Have anybody implemented an entity object over a XML file, i want to store some informations into a XML before connect to a database (the connection information) and be able to modify the data (create rows) using AF forms and tables.
Edited by: Fernando Ferpa Hackbart on Jun 18, 2009 5:39 PMyou have to write your own save/load functions, since you have to build your personnel xml document and then serilaize it
you can use nu.xom at this url
http://www.cafeconleche.org/XOM/apidocs/nu/xom/package-summary.html
to parse your document -
How to generate Java objects from XML files with out scema compilation
Dear participants,
My name is Raghavendra , i have a requirement of reading XML files Dynamically and parse them and create java types for manipulation . i will not be provided with sxd files (no schema compilation )coz no one knows how many types of structures are there. i want a generic solution. Please Help.
Thanks ,
Raghavendra Ach
you can mail me to " [email protected]"georgemc wrote:
You could also look at something like Apache Digester, which will parse your XML and populate Java objects with the data. A slightly steeper learning curve than the lower-level APIs such as JDOM, but that's outweighed by the lesser development effortdon't think that would work for the original problem, which seemed to indicate that the xml had an unknown structure. -
JAVA Object to XML to JAVA to XML
I have to achieve below in java:-
-Create input XMLs from Java class (that resides in a jar).
-Take input from user then store that data to Java object and submit for processing.
-After processing print response java object again in XML.
What is the best API to achieve this. Will be helpful if any example is available.Thanks for the Reply =)
I have a Java Object that have some fileds like arraylist<Class> I want to take care of these fields as well.
If that arrayList<Class> have another fields that can be normal fileds or arraylist of another class, need to take care of all fields during XML generation
Example:-
Root Class have below fields
private int ArCt;
private ArrayList<ClassChild1> Ar;
Setters
Getters
ClassChild1.class
private int PlnCd;
private int cArCt;
private ArrayList cAr<ClassChild2> cAr;
ClassChild2.class
private String PlNm
XML Needed - Example from above object
<root>
<ArCt>1</ArCt>
<Ar>
<ClassChild1>
<PlnCd>S</PlnCd>
<cArCt>2</<cArCt>
<cAr>
<ClassChild2>
<PlNm>Plan1</PlNm>
</ClassChild2>
<ClassChild2>
<PlNm>Plan2</PlNm>
</ClassChild2>
</cAr>
</ClassChild1>
</Ar>
</root>
Edited by: nitingautam on May 15, 2011 11:01 PM -
Errors while instantiated a custom java object within jsp pages.
I'm currently trying to role out a war file created on JavaBeans IDE 3.5.1. I have custom created classes
that are instantiated by using:
used.TransactionsHolder p_transactions = (used.TransactionsHolder) session.getAttribute("s_transactions");
Where used is the package and TransactionsHolder
is the class I am trying to create an object from. When
I use this syntax I receive this error:
__transactionPage.java:90: cannot resolve symbol
symbol : class TransactionsHolder
location: package used
used.TransactionsHolder p_transactions = (used.TransactionsHolder) session.getAttribute("s_transactions"); //[ transactionPage.jsp; Line: 12]
;Any suggestions?Can you please log a TAR with Oracle Support using Metalink to resolve this issue. They can help you collect all the log and trace files to determine the why this problem is occuring.
Business Intelligence Beans Product Management Team
Oracle Corporation
Maybe you are looking for
-
USB ports no longer working after 10.4.7 update
Hi, I ran the latest update (10.4.7) on my machine which is a G4 Quicksilver PowerPC. I have an Apple 17 inch flat screen display that has two USB ports attached. I had my keyboard plugged into one of the USB ports on my flat screen. After the update
-
Is there a Bug in Oracle 9.2.0.1
Dear all, I would like to have a solution for the following error. When I fire a select statement on table containing three date column fields. Statement is like this select staffno,to_date(fromdt,'DD-MON-YYYY'),to_date(todt,'DD-MON-YYYY'),to_date(ne
-
How do I calculate IRR using months, not years
When using the IRR funtion in Numbers for Mac (internal rate of return), how do I let the formula know that my time period is months and not years? In the Excel function, there is an extra arugment in the function that allows you to select the dates
-
EDI messages for ASN and POD - general flow
Hi, We are looking to send an Advance Shipping Notification Idoc / EDI message to our customer as we despatach and they will send a Proof Of Delivery EDI message to us confirming receipt and quantities. Am I right in saying that the customer MUST tak
-
IViews/Business Packages for News and/or Unit Converter
Hallo, are there any iViews or Business Packages available for the following tasks? 1. News iView with the possibility to refer to documents, have user (role) specific buttons (Create New, Edit, delete...) and Subscription Services using the cm-funct