Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing with SimpleXML

EDIT: Removed previous edit

I'm trying to deserialize the following:

<?xml version="1.0" encoding="UTF-8"?>
<ALL>
    <KAMP>
        <ID>1</ID>
        <SQLTID>1376881200</SQLTID>
        <DATO>2013-08-19</DATO>
    </KAMP>
    ...
    <KAMP>
        <ID>2</ID>
        <SQLTID>1376881200</SQLTID>
        <DATO>2013-08-19</DATO>
    </KAMP>
</ALL>

Using

@Root
public class Matches {

    @ElementList
    private List<Match> list;

    public List getMatches() {
        return list;
    }
}

And

@Root(name = "KAMP", strict = false)
public class Match{

    @Element(name = "ID", required = false)
    public String Id;

    @Element(name = "SQLTID", required = false)
    public String Sqltid;

    @Element(name = "DATO", required = false)
    public String MatchDate;
}

I keep getting

Element 'KAMP' does not have a match in class <myClass>

I've tried adding (name = "KAMP") to @ElementList but it didn't help.

Can anyone else help?

like image 666
CJe Avatar asked Mar 22 '23 17:03

CJe


1 Answers

The following code works for me, pay special attention to the following two items:

  1. empty constructor in ALL.java
  2. That the List has annotation of inline=true

ALL.java:

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import java.io.File;
import java.util.List;

/**
 * User: alfasin
 * Date: 8/19/13
 */
@Root(name="ALL")
public class ALL {

    @ElementList(entry="KAMP", inline=true)
    private List<KAMP> kamp;

    public ALL(){};

    public List<KAMP>  getMatches() {
        return kamp;
    }

    public static void main(String...args) throws Exception {
        Serializer serializer = new Persister();
        File example = new File("/Users/alfasin/Documents/workspace-sts-3.2.0.RELEASE/SimpleXML/src/kamp.xml");
        ALL all = serializer.read(ALL.class, example);
        for(KAMP tmp : all.getMatches()){
            System.out.println("ID: "+tmp.Id);
            System.out.println("MatchDate: "+tmp.MatchDate);
            System.out.println("Sqltid: "+tmp.Sqltid);
            System.out.println("----------");
        }
    }
}

KAMP.java

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * User: alfasin
 * Date: 8/19/13
 */
@Root(name="KAMP",strict = false)
public class KAMP {

    @Element(name = "ID", required = false)
    public String Id;

    @Element(name = "SQLTID", required = false)
    public String Sqltid;

    @Element(name = "DATO", required = false)
    public String MatchDate;

}

OUTPUT

ID: 1
MatchDate: 2013-08-19
Sqltid: 1376881200
----------
ID: 2
MatchDate: 2013-08-19
Sqltid: 1376881200
----------
like image 193
Nir Alfasi Avatar answered Apr 01 '23 08:04

Nir Alfasi