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
null

Rob 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

Similar Messages

  • 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.

  • 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.
    Paul

    Hi 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

  • Convert Serialized Java Objects to XML

    I have seen numerous ways that you can modify a java application to serlialize it's data as XML rather than a binary stream. Does anyone know if there are any utilities, libraries, DLLS, tools, whatever to convert an already serialized binary stream to an XML file.
    At the moment I am working on a script to do this, and it works for simple objects, but I am hitting snags as I test with more complicated class heirachies. I would love to find something that already does this for me.

    I want to read data serialized by a java program in a C++ application. I don't want to have to modify the java application, but I do want to make it's data available in other applications.
    I could modify the java app and serialize it's data in XML, but that isn't the prefered solution. :)

  • Converting Dom Document object into XML file removes the DTD

    Hi All
    My xml is dtd. I have one xml file. i changed the node value after that i want to create a xml file with the same name. I created new xml file but i am not seeing the old dtd in the new file. This process is done with the help of jaxp.
    My code is given below
    File fileInput = new File("input.xml");
              File fileOutput = new File("output.xml");
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setExpandEntityReferences(false);
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document document = builder.parse(fileInput);
              TransformerFactory tFactory = TransformerFactory.newInstance();
              Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "true");
              transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
              DOMSource source = new DOMSource(document);
              FileOutputStream fos = new FileOutputStream(fileOutput);
              StreamResult result = new StreamResult(fos);
              transformer.transform(source, result);
    Thanks in advance

    The Transformer API does not guarantee the preservation of that information. You may want to check the DOM L3 Load/Save package (http://java.sun.com/javase/6/docs/api/index.html). Alternatively, you may force things by setting the additional output properties 'doctype-public' and 'doctype-system'.

  • 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
    Orit

    How 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

  • 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.

  • Converting EJB Object into XML

    All:
    Suppose I have an EJB that is named MyDog, it has attributes as follows:
    name
    breed
    weight
    age
    Is there a way to convert this Object into an XML document? Something like:
    <?xml version=\"1.0\" ?>
    <MyDog>
    <name>Bubba</name>
    <breed>Australian Shepherd</breed>
    <weight>65 lbs</weight>
    <age>6 years old</age>
    </MyDog>
    I can't find any information on doing this - any ideas, links, etc? There has to be a way to do this, but I can't find it. I'm welcome to any ideas out there!

    check JAXB - might be usefull for you: http://java.sun.com/xml/jaxb/index.html

  • Converting Document object into XML file

    I was wondering how to convert a document object to XML file? I have read the documentation about document and Node but nothing explains the procedure of the conversion. Ive been told that it can be done, but not sure how. I have converted an XML file into Document by parsing DocumentBuilder. Just not sure how to do the reverse. Any help appreciated.

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.transform(new DOMSource(yourDOMsRootNode), new StreamResult(new FileOutputStream(yourFileName)));or something a lot like that.

  • How to convert Java string into XML one?

    With SAX I can parse an xml file, but I should create xml file by hands.
    Ok, it's simple, but how to encode java string into XML constant
    like "Hello & goodby" into "Hello & goodby" ?
    Is there a standard method for such special xml characters?

    If you are creating your XML "by hand" then just make sure your hands know that you have to do that. It isn't difficult to write a Java method to do it, if "by hand" means "in Java code". Otherwise your XML is not well-formed. And as far as I know there is no package that takes ill-formed XML and fixes it up.

  • XSLT Mapping to convert u201C.CSVu201D file into XML Structure.

    Hi All,
    I wanted to know can we use XSLT Mapping to convert u201C.CSVu201D file into XML Structure.
    I am communicating between two XI Systems. First XI system is going to give u201C.CSVu201D file as main document. I need to post IDOC Corresponding to this. So what I want to do is read this u201C.CSVu201D file (Main document in payload) and first convet it into XML and then use second mapping which will convert XML to IDOC.
    I know this is possible with JAVA Mapping but just wanted to confirm can we do this with XSLT mapping as well?
    Regards,
    Gouri

    Hi Amit,
    I know this way it shd work as i am able see other XSLT files. But this particular file is not visible.
    I am copying following code only in sample.xslt file.
    <xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:fn="fn"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      version="2.0" exclude-result-prefixes="xs fn">
    <xsl:output indent="yes" encoding="US-ASCII" />
    <xsl:param name="pathToCSV" select="'file:///c:/csv.csv'" />
    <xsl:function name="fn:getTokens" as="xs:string+">
        <xsl:param name="str" as="xs:string" />
        <xsl:analyze-string select="concat($str, ',')" regex='(("["]*")+|[,]*),'>
            <xsl:matching-substring>
            <xsl:sequence select='replace(regex-group(1), "^""|""$|("")""", "$1")' />
            </xsl:matching-substring>
        </xsl:analyze-string>
    </xsl:function>
    <xsl:template match="/" name="main">
        <xsl:choose>
        <xsl:when test="unparsed-text-available($pathToCSV)">
            <xsl:variable name="csv" select="unparsed-text($pathToCSV)" />
            <xsl:variable name="lines" select="tokenize($csv, ' ')" as="xs:string+" />
            <xsl:variable name="elemNames" select="fn:getTokens($lines[1])" as="xs:string+" />
            <root>
            <xsl:for-each select="$lines[position() &gt; 1]">
                <row>
                <xsl:variable name="lineItems" select="fn:getTokens(.)" as="xs:string+" />
                <xsl:for-each select="$elemNames">
                    <xsl:variable name="pos" select="position()" />
                    <elem name="{.}">
                    <xsl:value-of select="$lineItems[$pos]" />
                    </elem>
                </xsl:for-each>
                </row>
            </xsl:for-each>
            </root>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>Cannot locate : </xsl:text><xsl:value-of select="$pathToCSV" />
        </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    </xsl:stylesheet>
    Is this correct?
    -Gouri

  • Blaze DS - Mapping java object into another java application

    Good afternoon,
    I realized a Client-Server application. Server is Java-based. Client is Flex. Server services are accessible through Blaze DS.
    Now I have some Java clients that need to access server services. Blaze DS permits to do it simply but I don't know how to map java objects as I do using [RemoteClass(alias.....)] construct at Actionscript side.
    For example, server sends a MyObjectType and client receives an ASObject.
    Is there a way to map java MyObjectType automatically at destination?
    Thank you for help and sorry for poor english.
    Regards, Francesco

    xstream will convert any given java object to xml. Not sure what support it offers for schemas.
    http://xstream.codehaus.org/

  • Provide some code/API For Converting .EML & .DXL files

    Provide API or java code For Converting .EML & .DXL files into .TIFF as soon as possible.

    i also require some pointers to api that can convert .eml files to .msg files. Please let me know if there are any api's for the same.

  • Ignore some fields while saving a Java class into XML

    Hi!
    I've seen in this forum that there is an easy way of saving Java classes to XML files using Castor. I want to save some Java classes into XML, but not all the fields of the class. For example, I want to ignore all lists. Is there any easy way to do something like this:
    class Java2XML{
              public static void makeXML(Object object)
                        for all fields in object
                                  if field extends List, ignore
                                  else, include field in XML
    }Thanks in advance!

    You can add a managed bean by:
    - manually adding a definition in the faces config source tab.
    - creating a bean in the overview tab of the faces-config editor.
    So yes, you can edit the faces-config manually.
    I hope this answer your question,
    Regards,
    Koen Verhulst

Maybe you are looking for

  • How to find out who has deleted my query

    Dear SDNs, My query has been deleted in Prd system, so I want to know who did it. I try to get the log from SLG1 and SM21, but I can't get any information about the query deletion. I have also tried to read record from table RSRREPDIR, and this table

  • I can only delete one old bookmark at a time. How can I delete mutiple old bookmarks at once?

    ''dupe of https://support.mozilla.org/en-US/questions/911712'' I can only delete one bookmark at a time? How Can I delete mutiple old bookmarks?

  • WRT600n

    My laptop is currently using a Netgear USB WG111v2 802,11g wireless adapter (the laptop's internal wirless G adapter died) with the WRT600N. Usually on powering up the laptop, I initially can't get any internet access at all, even though the Netgear

  • Sort order notes iOS 6.0

    Since it is finally possible to sort my Notes with MacOS 10.8.2 I am desperately seeking for the same possibility on my iPhone and iPad (iOS 6.0). It does neither use the sort-order (alphabetically!!!) from my desktop Mac nor am I able to change the

  • Creating customer fields in VA01/Va02 transaction in additonal tab 2

    hi,     I have to create Customer fields in the item level to va01 / va02 transaction in additional tab 2 subscreen. Include MV45AFZZ is used for validation. help needed for adding customer fields. thanks in advance.