简体   繁体   中英

creating objects while reading xml in java

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 Employee node is nested within the Company node, so you might need to do some extra work. As is, your XML would at most be rendered in a class named Company which has a list of Employees .

Note however, you will need to have the classes which match the XML available before hand.

You say:

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

Why's that ? It seems a simple and intuitive way to do this (eg using a SAX parser). However, if you don't want to reinvent the wheel (that's very understandable), then I would check out XStream or JAXB .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM