[英]Trying to convert an object array into XML, can't get object headers
我正在使用这个XML转换器,但是我没有得到对象标头来包装每个对象的属性...在编码器类中也找不到方法来执行此操作。
该代码遍历我的数组并列出所有不为null的对象。
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文件读取到数组中无济于事……对此的任何帮助也将非常有用!
编辑:基于给定答案的新信息:
因此,没有no-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;
}
有什么建议么?
序列化对象实例变量将导致难以维护的过程,在该过程中,您将被迫将值逐一解码。
序列化整个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
类符合JavaBeans约定,而JavaBeans约定基本上必须是可Serializable
并且应该提供公共的无参数构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.