Search code examples
androidpropertiesattributesksoap2

Ksoap2 Android adding Attributes to a simple property


I am trying to create a new property inside a SoapObject that will contain simple string properties with attributes to them like this:

<Power Unit="kw">1500</Power>

here is the code i am using for my samples below.

final SoapObject powerObject= new SoapObject(namespace, "Power");
        powerObject.addAttribute("Unit", getPowerUnit());

        PropertyInfo powerObjectProperty = new PropertyInfo();
        powerObjectProperty .setName("");
        powerObjectProperty .type = String.class;
        powerObjectProperty .setValue(getPower());
        powerObjectProperty .addProperty(powerObjectProperty);
        root.addSoapObject(powerObject); // this is my root for the hierarchy

The best that i could reach is the following:

<Power Unit="kw"><>1500</></Power>

i even tried to add everything as a string but that encodes the <> tags.

&ltPower Unit"kw"&gt1500&lt/Power&gt

I am using:

ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar on android.


Solution

  • Ok i have solved this issue, here is how:

    I have created a new soap object called TextSoapObject

    public class TextSoapObject extends SoapObject {
        public static final String TAG = TextSoapObject.class.getSimpleName();
    
        public TextSoapObject(String namespace, String name) {
            super(namespace, name);
        }
    
        public String text;
    
        public void setText(String text) {
            this.text = text;
        }
    
        public String getText() {
            return text;
        }
    }
    

    Next i overrided SoapSerialization envelope like this:

    public class ValueSerializationEnvelope extends SoapSerializationEnvelope {
    
        public ValueSerializationEnvelope(int version) {
            super(version);
        }
    
        public static final String TAG = ValueSerializationEnvelope.class.getSimpleName();
    
    
        @Override
        public void writeObjectBody(XmlSerializer writer, KvmSerializable obj) throws IOException {
            if (obj instanceof TextSoapObject) {
                writer.text(((TextSoapObject) obj).getText());
            }
            super.writeObjectBody(writer, obj);
        }
    }
    

    And that's it.

    To use this you would do the following:

    final TextSoapObject costOfRepairs = new TextSoapObject(namespace, "CostOfRepairs");
            costOfRepairs.addAttribute("Currency", getCurrency());
            costOfRepairs.setText(getRepairCosts() + "");
            root.addSoapObject(costOfRepairs);
    

    EDIT:

    This issue has been recognized for the ksoap2 library and addressed here:

    http://code.google.com/p/ksoap2-android/issues/detail?id=112

    Should be fixed in the next ksoap2 Release.