1

I am trying to create elements from an xml using simple xml for android and I am not interested in the root, but only some nested elements. I am only interested in getting account object from the below xml.

<response xmlns="http://abc.abcdef.com/rest/xyz">
    <request>
        <channel>334892326</channel>
        <number>486</number>
    </request>
    <status>
        <code>200</code>
    </status>
    <results>
        <account>
            <creationTimestamp>2014-01-12T1:31:07Z</creationTimestamp>
            <category>
                <type>User-1</type>
                <name>User-1</name>
            </category>
        </account>
    <results>
</response>

I have tried the following in the bean, but my resulting object is containing all values as null.

@Root(strict = false, name = "account")
@Path("response/results/account")
public class Account implements Serializable {

    @Element(required = false)
    private String creationTimestamp;

    @Element(required = false)
    private Category category;
}

1 Answer 1

2

At first specified XML isn't well-formed. But the main issue is caused by Path annotation - "... to map attributes and elements to an associated field or method", it doesn't work with classes, only with methods and fields.

So this code parses your XML structure easily (simplified version):

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;

import java.io.File;

@Root(strict = false)
public class Account {

    @Element
    @Path("results/account")
    String creationTimestamp;

    @Element
    @Path("results/account")
    Category category;

    public static void main(String[] args)
            throws Exception
    {
        Account account = new Persister().read(Account.class, new File("example.xml"));

        System.out.println(account.creationTimestamp);
        System.out.println(account.category.type);
        System.out.println(account.category.name);
    }
}

@Root
class Category {

    @Element
    String type;

    @Element
    String name;
}

Unfortunately @Path annotation couldn't be extracted as class annotation, that's why you have to write it for every field.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it really needed to create the Response class. Can't I directly get it into Account?
Yes, you can, I updated the code - just one thing - without Response class you have to repeat @Path annotation for every field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.