Search code examples
javaxmlparsingxstream

XML mapping attribute of nested element


I'm using XStream and I have an XML sample:

<person>
    <firstname>Joe</firstname>
    <lastname>Walnes</lastname>
    <phone value="1234-456" />
    <fax value="9999-999" />
</person>

and I whant to map it to the class

public class Person {

    private String firstname;
    private String lastname;
    private String phone;
    private String fax;

}

So the idea is to map attribute of nested element to the current object. I tried to find any ready-to-use converter with no success. I believe that's possible by implementing new converter but may be someone already did this. Or there's a solution I haven't found.

Updated:

The idea I'm trying to implement is omitting unnecessary entities of being created and mapped. I don't need Phone and Fax entities at all, I need only their attributes in my model. The XML schema I'm trying to parse is thirdparty for me and I can't change it.


Solution

  • I don't know of a ready-to-use converter that will do it, but it's pretty trivial to write one

    import com.thoughtworks.xstream.converters.*;
    import com.thoughtworks.xstream.io.*;
    
    public class ValueAttributeConverter implements Converter {
      public boolean canConvert(Class cls) {
        return (cls == String.class);
      }
    
      public void marshal(Object source, HierarchicalStreamWriter w, MarshallingContext ctx) {
        w.addAttribute("value", (String)source);
      }
    
      public Object unmarshal(HierarchicalStreamReader r, UnmarshallingContext ctx) {
        return r.getAttribute("value");
      }
    }
    

    You can attach the converter to the relevant fields using annotations

    import com.thoughtworks.xstream.annotations.*;
    
    @XStreamAlias("person")
    public class Person {
    
        private String firstname;
        private String lastname;
    
        @XStreamConverter(ValueAttributeConverter.class)
        private String phone;
    
        @XStreamConverter(ValueAttributeConverter.class)
        private String fax;
    
        // add appropriate constructor(s)
    
        /** For testing purposes - not required by XStream itself */
        public String toString() {
          return "fn: " + firstname + ", ln: " + lastname +
                 ", p: " + phone + ", f: " + fax;
        }
    }
    

    To make this work, all you need to do is instruct XStream to read the annotations:

    XStream xs = new XStream();
    xs.processAnnotations(Person.class);
    Person p = (Person)xs.fromXML(
      "<person>\n" +
      "  <firstname>Joe</firstname>\n" +
      "  <lastname>Walnes</lastname>\n" +
      "  <phone value='1234-456' />\n" +
      "  <fax value='9999-999' />\n" +
      "</person>");
    System.out.println(p);
    // prints fn: Joe, ln: Walnes, p: 1234-456, f: 9999-999