I was wondering something about xml parsing in java. While I’m reading xml file in java, is it possible to create simultaneously objects of xml tags. Let me give an example.
This is my xml file. I read it. I can get firstname lastname etc… While reading it, i want to create an employee object with firtname and lastname values. I know that I can create an employee class and when I’m reading data I can assign values to this class but I don’t want to do it in this way. Does java provide any easier way to create an employee object. I hope it is clear what I mean.
<company>
<employee>
<firstname>Tom</firstname>
<lastname>Cruise</lastname>
</employee>
<employee>
<firstname>Paul</firstname>
<lastname>Enderson</lastname>
</employee>
<employee>
<firstname>George</firstname>
<lastname>Bush</lastname>
</employee>
You could try and use
XStream. It should allow you to create objects in a very simple manner (from their 2-minute tutorial), you could do something like so:Employee emp = (Employee)xstream.fromXML(xml);However, note that your
Employeenode is nested within theCompanynode, so you might need to do some extra work. As is, your XML would at most be rendered in a class namedCompanywhich has a list ofEmployees.Note however, you will need to have the classes which match the XML available before hand.