0

我想知道关于 java 中的 xml 解析的一些事情。当我在 java 中读取 xml 文件时,是否可以同时创建 xml 标签的对象。让我举个例子。这是我的 xml 文件。我读了。我可以得到 firstname lastname 等...在阅读它时,我想创建一个具有 firtname 和 lastname 值的员工对象。我知道我可以创建一个员工类,当我读取数据时,我可以为这个类分配值,但我不想这样做。java 是否提供任何更简单的方法来创建员工对象。我希望我的意思很清楚。

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

4

2 回答 2

1

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.

于 2012-08-08T08:28:02.310 回答
1

你说:

我知道我可以创建一个员工类,当我读取数据时,我可以为这个类分配值,但我不想这样做

为什么 ?这似乎是一种简单而直观的方法(例如,使用 SAX 解析器)。但是,如果您不想重新发明轮子(这很容易理解),那么我会检查XStreamJAXB

于 2012-08-08T08:33:55.213 回答