Samraan
Samraan

Reputation: 214

How to convert XML to Java Object without know the structure of the Object through XStream Library

If we know the structure of the object the with help of "useAttributeFor" method and aliases we can mapped the same tag name and class variable. But my requirement is that convert the xml file to object without knowing the object structure. For Example we hava a xml file test.xml with contect as:

<test>
     <Name>John</Name>
     <age>18</age>
</test>

Now I need to convert this xml file into object. My Java Class will be like:

 public class Test
 {
    private String Name;
    private int age;
    public void setName(String Name,int age)
    {
       this.Name = Name;
       this.age = age;
    }
    public void display()
    {
       System.out.println("Name: "+Name);
       System.out.println("Age: "+age);
    }
 }

I'm new to this so please help me out and thank you all in advance

Upvotes: 0

Views: 891

Answers (1)

onacione
onacione

Reputation: 74

Suppose you have a requirement to load configuration from xml file.

<test>
     <name>John</name>
     <age>18</age>
</test>

And you want to load it into Configuration object:

public class Test
 {
    private String name;
    private int age;
    public void setName(String name,int age)
    {
       this.name = name;
       this.age = age;
    }
    public void display()
    {
       System.out.println("Name: "+name);
       System.out.println("Age: "+age);
    }
 }

you have to do is:

    FileReader fileReader = new FileReader("test.xml");  // load your xml file 
    XStream xstream = new XStream();     // init XStream
    // define root alias so XStream knows which element and which class are equivalent
    xstream.alias("test", Test.class);   
    Test test = (Test) xstream.fromXML(fileReader);`

that’s all !

Upvotes: 3

Related Questions