0

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

Samraan
  • 204
  • 1
  • 2
  • 14
  • If this is possible at all, I would think it's somehow done via Reflection. But given the static typesafety nature of Java, I kind of doubt it's doable - I would probably read the XML file into some kind of Map instead. Unless maybe it's possible to create new .class files and load them in at runtime? IDK, that's way beyond what I know how to do in Java. – ArtOfWarfare Dec 17 '14 at 15:25
  • Here you go, this answer looks like it covers how to compile new classes and load them in at run time... I suspect you can somehow utilize this: http://stackoverflow.com/a/2946402/901641 – ArtOfWarfare Dec 17 '14 at 15:27

1 Answers1

3

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 !

onacione
  • 74
  • 2
  • Your answer requires the Test class to be created in advance. The question was asking how to do this without the Test class already existing. – ArtOfWarfare Dec 17 '14 at 15:23
  • @onacione : Thanks for your response but here notice test in xstream.alias("test", Test.class) It means you in advance that in test is a tag in xml file. Suppose we don't know the tag name in advance. It want this to be generic – Samraan Dec 18 '14 at 04:23