Reputation: 185
I am using SimpleXML for Java to parse a XML response to java class mapping. However, I am not able to get this particular piece working with my android device.
My XML fragment looks like this,
<t:EmailAddresses>
<t:Entry Key="EmailAddress1">sip:[email protected]</t:Entry>
<t:Entry Key="EmailAddress2">smtp:[email protected]</t:Entry>
<t:Entry Key="EmailAddress3">SMTP:[email protected]</t:Entry>
</t:EmailAddresses>
and my Class definition for EmailAddresses looks like this,
@Root
public class EmailAddresses
{
@ElementList
private List<Entry> Entry;
public List<Entry> getEntry() { return Entry; }
public void setEntry(List<Entry> entry) { Entry = entry; }
}
And my Entry class looks like this,
@Element
public class Entry
{
@Attribute
private String Key;
public String getKey() { return Key; }
public void setKey(String key) { Key = key; }
}
when I parse run the parser, I only get the Keys and that also, I get "Multiple Root Elements" error when trying to parse all 3 into a List of Entry class.
Can someone please point me in the right direction?? Thanks !!
Note: The XML Namespace "t" is defined properly.
Upvotes: 3
Views: 3376
Reputation: 4836
Can you not use attributes to extract the data? Here's a snippet from an RSS feed reader app that parses XML similarly:
if (localName.equals("channel"))
{
/** Get attribute value */
String attr = attributes.getValue("category");
itemList.setTitle(attr);
}
Upvotes: 0
Reputation: 25370
Here are some things you should change:
Class EmailAddresses
@Root(name = "EmailAddresses") /* 1 */
@Namespace(prefix = "t", reference = "INSERT YOUR REFERENCE HERE!") /* 2 */
public class EmailAddresses
{
@ElementList(inline = true) /* 3 */
private List<Entry> Entry;
// ...
}
Explanation:
/* 1 */
: Set the name of the element (case sensitive); simple does this per default, but so you can ensure it's really correct./* 2 */
: Set the namespace and it's reference; required for the t
in your XML./* 3 */
: Inline the list; the <t:EmailAddresses>
element is constructed out of the @Root()
element, all entries follow as
inline-elements. Otherwise the list will create another element as child,
wrapping it's entries.Class Entry
@Root(name = "Entry") /* 1 */
@Namespace(prefix = "t", reference = "INSERT YOUR REFERENCE HERE!") /* 2 */
public class Entry
{
@Text
private String text; /* 3 */
@Attribute
private String Key;
// ...
}
Explanation:
/* 1 */
: Don't use @Element
here, use @Root()
./* 2 */
: As #2 above./* 3 */
: Your Entry
-tags in the XML contain text (= value of the element, like the "sip:..."), those require a mapping too. If the text is optional, you can use @Text(required = false)
to indicate that.TIP: Create an instance of your list, fill it with entries and serialize it, e.g. into a file. So you can see if the mapping is matching your expectations, and where you have to do some corrections.
Upvotes: 8