用于XML解析的Android SimpleXML库

时间:2013-08-23 06:22:15

标签: java android xml simple-framework

我正在使用SimpleXML库解析一个长xml。这是Long XML的链接

http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml

现在我想要指导 im:图片标签

我做了以下POJO课程

public class Image {
private int height;

public Image(@Attribute(name = "height") int height)
{
    this.height=height;
}
@Attribute(name = "height") 
public int getObjectHeight() {
    return height;
}
}

但这看起来不正确,因为它只会处理高度......如何解析这些标签之间的内容

<im:image height="170"> </im:image>

我的第二个问题是java中的变量名是什么...因为在java中不允许使用im:image。

请尽快帮助我。

由于

2 个答案:

答案 0 :(得分:0)

首先,您需要为元素添加命名空间

@Namespace(reference = "http://itunes.apple.com/rss", prefix = "im")
public class Image {
   @Element(name = "image ")
   private String image_url;

   @Attribute
   private int height;
}

答案 1 :(得分:0)

下一个代码可以正常运行

@Root(name = "feed")
static class Feed {
    @Element
    Image image;

}

@Root(name = "image")
static class Image {

    @Attribute(name = "height")
    int height;

    @Text
    String content;

}

@Test
public void testPrefixedTag() throws Exception {
    String xml = 
            "<feed xmlns:im=\"http://itunes.apple.com/rss\" xmlns=\"http://www.w3.org/2005/Atom\">" +
            "<im:image height=\"170\">Content</im:image>" +
            "</feed>";
    Serializer serializer = new Persister();
    Feed feed = serializer.read(Feed.class, xml);
}

因此,如果您在根标记中引用im命名空间(链接的xml有一个),您可以使用没有它的子标记的名称(在我们的例子中为image

要解析标记之间的内容,请使用@Text注释。