Search code examples
javaarraysxmlobjectxmlencoder

Trying to convert an object array into XML, can't get object headers


I'm using this XML converter, but I am not getting the object header to wrap each object's properties... I can't find a method in the encoder class to do this either.

The code iterates through my array and lists all objects that are not 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(); 

I get this outcome:

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

If I do more object entries then it ends up being a big list which isn't helpful as another function I want to implement is reading from an XML file into the array... any help on that would also be useful!

EDIT: New information based on the answer given:

So is there no way to make this happen without a no-arg constructor? I've implemented the Serializable into both classes for good measure... I'm using this line to add new objects:

mybook1.addRecord(new newPerson(Name,telephoneNumber,emailAddress));  

which uses this:

public void addRecord(newPerson c) 
{
    people[numOfRecords] = c; 
    numOfRecords++;  
}                                                               

below is the object itself:

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

Any suggestions?


Solution

  • Serializing Object instance variables will result in a hard to main process where you will be forced to decode the values back one by one.

    It would be wiser and easier to deal with when serializing your whole People objects:

    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(); 
    

    Meanwhile, you have to make sure that your People class statisfies the JavaBeans conventions which basiclly has to be Serializable and should provide a public no-arg constructor.