我正在使用这个XML转换器,但是我没有得到对象头来包装每个对象的属性.我在编码器类中也找不到这样的方法。
代码遍历我的数组并列出所有非空对象。
FileOutputStream os = new FileOutputStream("C:\\Users\\David Laptop\\Documents\\Doc1.xml");
XMLEncoder encoder = new XMLEncoder(os);
for( int x = 0; x < people.length;x++)
if (people[x] != null)
{
//header here?
encoder.writeObject(people[x].getName());
encoder.writeObject(people[x].getTelephoneNumber());
encoder.writeObject(people[x].getEmailAddress());
}
}
encoder.close(); 我得到这样的结果:
<?xml version="1.0" encoding="UTF-8" ?>
<java version="1.7.0_40" class="java.beans.XMLDecoder">
string
dad</string string 35235 /string
string email /string
</java>如果我做了更多的对象条目,那么它最终是一个大列表,这是没有帮助的,因为我想实现的另一个函数是从XML文件中读取到数组中.在这方面的任何帮助也是有用的!
编辑:基于给出的答案的新信息:
那么,如果没有非arg构造函数,就无法实现这一点吗?我已经在两个类中实现了Serializable,以便进行良好的度量.我使用这一行来添加新的对象:
mybook1.addRecord(new newPerson(Name,telephoneNumber,emailAddress)); 它使用以下内容:
public void addRecord(newPerson c)
{
people[numOfRecords] = c;
numOfRecords++;
} 以下是对象本身:
public class newPerson implements java.io.Serializable
{
private String Name;
private String telephoneNumber;
private String emailAddress;
public newPerson(String n, String t, String e)
{ //local variables n,t,e only used in this method
Name = n;
telephoneNumber = t;
emailAddress = e;
}有什么建议吗?
发布于 2014-11-13 15:23:36
序列化对象实例变量将导致从主进程到主进程的困难,您将被迫逐个解码返回的值。
在序列化整个People对象时,它将更明智和更容易处理:
FileOutputStream os = new FileOutputStream("C:\\Users\\David Laptop\\Documents\\Doc1.xml");
XMLEncoder encoder = new XMLEncoder(os);
for( int x = 0; x < people.length;x++)
if (people[x] != null)
{
encoder.writeObject(people[x]);
}
}
encoder.close(); 同时,您必须确保您的People类统计了基本必须是Serializable的JavaBeans约定,并且应该提供一个公共的无arg构造函数。
https://stackoverflow.com/questions/26910437
复制相似问题