2

I am trying to use JAXB implementation to convert my class objects to XML and vice versa. I implemented this by observing a tutorial.

My XML looks like this

<Alphabet>
    <a>Apple</a>
    <b>Ball</b>
    <c>Cat</c> 
    <d>Dog</d>
    <e>Elephant</e>
    <f>Fox</f>
</Alphabet>

I wrote the following classes

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Alph {

    @XmlElement
    private LinkedHashMap<String, String> cLinkedHashMap = new 
            LinkedHashMap<String, String>();

    protected void put(String theKey, String theValue) {
        cLinkedHashMap.put(theKey, theValue);   
    }

    protected String get(String theKey) {
        return (String) cLinkedHashMap.get(theKey);
    }

    protected Set<Entry<String,String>> getCEntrySet() {
        return cLinkedHashMap.entrySet();
    }

    protected LinkedHashMap<String, String> getCLinkedHashMap() {
        return cLinkedHashMap;
    }

    public String toCXML() throws XMLHandlingException {
        return null;
    }

}

@XmlRootElement
public class Alphabet extends Alph {

    public static Alphabet getInstance(String theAlphabetXML) throws 
    XMLHandlingException {
        return XMLUtils.parseAlphabetXML(theAlphabetXML);
    }

    public String toCXML() throws XMLHandlingException {
        return XMLUtils.getAlphabetXML(this);
    }

}

I created the following XMLUtil Methods for marshalling and unmarshalling

public static String getAlphabetXML(Alph theAlphabet) throws XMLHandlingException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Writer writer = null;
    try {
        writer = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    try {
        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" );
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        JAXBContext JContext = JAXBContext.newInstance(Alphabet.class); 
        Marshaller JMarshaller = JContext.createMarshaller();
        JMarshaller.marshal(theAlphabet, writer);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    String theAlphabetXML = byteArrayOutputStream.toString();
    return theAlphabetXML;
}

public static Alphabet parseAlphabetXML(String theAlphabetXML) throws 
XMLHandlingException {

    if(null == theAlphabetXML) {
        return null;
    }
    try {
        InputStream IPStream = new ByteArrayInputStream(theALphabetXML.getBytes());
        JAXBContext JContext = JAXBContext.newInstance(Alphabet.class);
        Unmarshaller JUnmarshaller = JContext.createUnmarshaller();
        Alphabet alphabet = (Alphabet) JUnmarshaller.unmarshal(IPStream);
        return alphabet;
    } catch(Throwable t) {
        t.printStackTrace();
    }
}

My problem is that when ever I try to marshal or unmarshal I am getting the follwoing error "javax.xml.bind.UnmarshalException: unexpected element (a:"", local:"Alphabet"). Expected elements are <{}Alphabet>"

Did I miss something? Any help is appreciated.

Thanks


Update


I followed http://blog.bdoughan.com/2013/06/moxys-xmlvariablenode-using-maps-key-as.html and updated my code as follows

Request and response XML

<AlphabetReq>
    <a>Apple</a>
    <b>Ball</b>
    <c>Cat</c> 
    <d>Dog</d>
    <e>Elephant</e>
    <f>Fox</f>
</AlphabetReq>

<AlphabetResp>
    <a>Apple</a>
    <b>Ball</b>
    <c>Cat</c> 
    <d>Dog</d>
    <e>Elephant</e>
    <f>Fox</f>
</AlphabetResp>

AlphabetReq and AlphabetResp classes

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Alph {

@XmlPath(".")
@XmlJavaTypeAdapter(AlphAdapter.class)
private LinkedHashMap<String, String> cLinkedHashMap = new 
        LinkedHashMap<String, String>();

@XmlPath(".")
@XmlJavaTypeAdapter(AlphAdapter.class)
private LinkedHashMap<String, String> gLinkedHashMap = new 
        LinkedHashMap<String, String>();

protected void put(String theKey, String theValue) {
    cLinkedHashMap.put(theKey, theValue);   
    gLinkedHashMap.put(theKey, theValue);
}

protected String get(String theKey) {
    return (String) cLinkedHashMap.get(theKey);
}

protected Set<Entry<String,String>> getCEntrySet() {
    return cLinkedHashMap.entrySet();
}

protected Set<Entry<String,String>> getGEntrySet() {
    return gLinkedHashMap.entrySet();
}

protected LinkedHashMap<String, String> getCLinkedHashMap() {
    return cLinkedHashMap;
}

protected LinkedHashMap<String, String> getGLinkedHashMap() {
    return gLinkedHashMap;
}

public String toCXML() throws XMLHandlingException {
    return null;
}

public String toGXML() throws XMLHandlingException {
    return null;
}

}

@XmlRootElement(name="AlphReq")
@XmlDiscriminatorValue("AlphabetReq")
@XmlAccessorType(XmlAccessType.FIELD)
public class AlphabetReq extends Alph {

public static AlphabetReq getInstance(String theAlphabetReqXML) throws 
XMLHandlingException {
    return XMLUtils.parseAlphabetReqXML(theAlphabetReqXML);
}

public String toCXML() throws XMLHandlingException {
    return XMLUtils.getAlphabetReqXML(this);
}

}

@XmlRootElement(name="AlphResp")
@XmlDiscriminatorValue("AlphabetResp")
@XmlAccessorType(XmlAccessType.FIELD)
public class AlphabetResp extends Alph {

public static AlphabetResp getInstance(String theAlphabetRespXML) throws 
XMLHandlingException {
    return XMLUtils.parseAlphabetRespXML(theAlphabetRespXML);
}

public String toCXML() throws XMLHandlingException {
    return XMLUtils.getAlphabetRespXML(this);
}

}

I created the following XMLUtil Methods for marshalling and unmarshalling

public static String getAlphabetReqXML(Alph theAlphabet) throws XMLHandlingException {

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Writer writer = null;

try {
    writer = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

try {
    writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" );
} catch (IOException e) {
    e.printStackTrace();
}

try {
    JAXBContext JContext = JAXBContext.newInstance(AlphabetReq.class); 
    Marshaller JMarshaller = JContext.createMarshaller();
    JMarshaller.marshal(theAlphabet, writer);
} catch (Throwable e) {
    e.printStackTrace();
}

String theAlphabetReqXML = byteArrayOutputStream.toString();
return theAlphabetReqXML;

}

public static AlphabetReq parseAlphabetReqXML(String theAlphabetReqXML) throws 
XMLHandlingException {

if(null == theAlphabetReqXML) {
    return null;
}
try {
    InputStream IPStream = new ByteArrayInputStream(theAlphabetReqXML.getBytes());
    JAXBContext JContext = JAXBContext.newInstance(AlphabetReq.class);
    Unmarshaller JUnmarshaller = JContext.createUnmarshaller();
    AlphabetReq alphabetreq = (AlphabetReq) JUnmarshaller.unmarshal(IPStream);
    return alphabetreq;
} catch(Throwable t) {
    t.printStackTrace();
}
}

public static String getAlphabetRespXML(Alph theAlphabet) throws XMLHandlingException {

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Writer writer = null;

try {
    writer = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

try {
    writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" );
} catch (IOException e) {
    e.printStackTrace();
}

try {
    JAXBContext JContext = JAXBContext.newInstance(AlphabetResp.class); 
    Marshaller JMarshaller = JContext.createMarshaller();
    JMarshaller.marshal(theAlphabet, writer);
} catch (Throwable e) {
    e.printStackTrace();
}

String theAlphabetRespXML = byteArrayOutputStream.toString();
return theAlphabetRespXML;

}

public static AlphabetResp parseAlphabetReqXML(String theAlphabetRespXML) throws 
XMLHandlingException {

if(null == theAlphabetRespXML) {
    return null;
}
try {
    InputStream IPStream = new ByteArrayInputStream(theAlphabetRespXML.getBytes());
    JAXBContext JContext = JAXBContext.newInstance(AlphabetResp.class);
    Unmarshaller JUnmarshaller = JContext.createUnmarshaller();
    AlphabetResp alphabetresp = (AlphabetResp) JUnmarshaller.unmarshal(IPStream);
    return alphabetresp;
} catch(Throwable t) {
    t.printStackTrace();
}
}

and introduced an Adapter class

import java.util.*;
import java.util.Map.Entry;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.eclipse.persistence.oxm.annotations.XmlVariableNode;

public class AlphAdapter extends XmlAdapter<AlphAdapter.AdaptedMap, LinkedHashMap<String, String>>{

public static class AdaptedMap {
    @XmlVariableNode("key")
    List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();  
}

public static class AdaptedEntry {  
    @XmlTransient
    public String key;

    @XmlValue
    public String value;
}

@Override
public AdaptedMap marshal(LinkedHashMap<String, String> map) throws Exception {
    AdaptedMap adaptedMap = new AdaptedMap();
    for(Entry<String, String> entry : map.entrySet()) {
        AdaptedEntry adaptedEntry = new AdaptedEntry();
        adaptedEntry.key = entry.getKey();
        adaptedEntry.value = entry.getValue();
        adaptedMap.entries.add(adaptedEntry);
    }
    return adaptedMap;
}

@Override
public LinkedHashMap<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
    List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(adaptedEntries.size());
    for(AdaptedEntry adaptedEntry : adaptedMap.entries) {
        map.put(adaptedEntry.key, adaptedEntry.value);
    }
    return map;
}
}

When I run this I am not getting any values into my adaptedmap. it has keys but values as null for ex:

  • key: A, value: null
  • key: B, value: null
  • key: C, value: null
  • key: D, value: null
  • key: E, value: null
  • key: F, value: null

Any help is appreciated.

Thanks

kvbrahmam
  • 143
  • 2
  • 14
  • `catch (Throwable e) { return null; }` - don't do that. It will make debugging impossible – artbristol Aug 30 '13 at 12:57
  • 2
    The following may be what you are looking for: http://blog.bdoughan.com/2013/06/moxys-xmlvariablenode-using-maps-key-as.html – bdoughan Aug 30 '13 at 13:35
  • Hello @BlaiseDoughan , I followed your link and updated my code, it still errors out. Any help is appreciated. thanks – kvbrahmam Sep 11 '13 at 08:32

2 Answers2

1

You can achieve this simple XML creation (that you have given) as below :

@XmlRootElement
public class Alphabet {
    private String a;
    private String b;
    private String c;
    private String d;
    private String e;
    private String f;

    public Alphabet() {

    }

    public Alphabet(String a, String b, String c, String d, String e, String f) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
        this.f = f;
    }

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }

    public String getE() {
        return e;
    }

    public void setE(String e) {
        this.e = e;
    }

    public String getF() {
        return f;
    }

    public void setF(String f) {
        this.f = f;
    }

}

This class is to create the xml file :

public class AlphabetToXML {
    public static void main(String[] args) {
        Alphabet alpha = new Alphabet("Apple", "Ball", "Cat", "Dog",
                "Elephant", "Fox");
        try {
            String filePath = "PATH_TO_SAVE_YOUR_FILE";
            File file = new File(filePath);
            JAXBContext jaxbContext = JAXBContext.newInstance(Alphabet.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(alpha, file);
            jaxbMarshaller.marshal(alpha, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

And this is to read your XML back to Java object :

public class XMLToAplhabet {
    public static void main(String[] args) {
        try {
            String filePath = "XML_FILE_PATH";
            File file = new File(filePath);
            JAXBContext jaxbContext = JAXBContext.newInstance(Alphabet.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Alphabet aplha = (Alphabet) jaxbUnmarshaller.unmarshal(file);
            System.out.println(aplha);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

I don't see any use of LinkedHashMap to create a simple XML like this.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46
  • Hello Debojit Saikia, Sorry In my question I gave a example XML, My XML is going to have a lots of elements under root . I don't think the above Implementation going to work. Thanks – kvbrahmam Aug 30 '13 at 13:21
  • +1 - BTW, I removed the unnecessary `@XmlElement` annotations. – bdoughan Aug 30 '13 at 13:23
  • Is it possible for you to give an example of your XML file? that will help you to get correct answers. Thanks. – Debojit Saikia Aug 30 '13 at 13:26
  • Hello Debojit Saikia, my XML input will be dynamic, this is why I am using a hashmap. so what ever I keep inside tag should be processed. Thanks – kvbrahmam Aug 30 '13 at 13:31
  • I think [this discussion](http://stackoverflow.com/questions/7273615/java-unmarshlling-xml-to-object-which-are-dynamic) will answer all your queries. Thanks. – Debojit Saikia Aug 30 '13 at 13:48
  • Hello @DebojitSaikia , I updated my code, it still errors out. Any help is appreciated. thanks – kvbrahmam Sep 11 '13 at 09:06
1

http://java.dzone.com/articles/jaxb-and-javautilmap might be helpful. Contains different ways for doing the same task.

Sarath
  • 1,438
  • 4
  • 24
  • 40