Menu

16 Şubat 2011 Çarşamba

Groovy ile Java Objectlerini XML cevirme

Person.java

public class Person {

    private String name;
    private String surname;
    private Contact[] contacts;

    public Person(String name, String surname, Contact[] contacts) {
        this.name = name;
        this.surname = surname;
        this.contacts = contacts;
    }
..

}

Contact.java

public class Contact {

    private String address;
    private String city;

    public Contact(String address, String city) {
        this.address = address;
        this.city = city;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

Test.groovy

def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)

Contact[] cts = new Contact[1];
cts[0] = new Contact("Resid Beh","Baku");
Person per = new Person("Ertugrul", "Aslan",cts)
Contact[] cts2 = new Contact[2];
cts2[0] = new Contact("Nizami","Gence");
cts2[1] = new Contact("Merkez","Sumgayit");
Person per2 = new Person("Hakan", "Dogan",cts2)

java.util.List prs = new java.util.ArrayList()
prs.add(per)
prs.add(per2)

def ob = prs

xml.truck(id:'TestData'){
    persons(){
        ob.eachWithIndex(){
            obj, i ->
            person(){
                name(ob.get(i).getName())
                surname(ob.get(i).getSurname())
                contacts(){
                    ob.get(i).getContacts().eachWithIndex(){
                        objx, x ->
                        contact(){
                            address(objx.getAddress())
                            city(objx.getCity())
                        }
                    }
                }
            }
        }
    }
}

println writer.toString()

//def target = "c:/test.xml"
//File file= new File(target)
//PrintWriter pw = new PrintWriter(file)
//pw.write("\n")
//pw.write(writer.toString())
//pw.flush()
//pw.close()

Hiç yorum yok:

Yorum Gönder