【发布时间】:2017-12-13 19:12:46
【问题描述】:
如何在 android 中解析具有这种结构的文件?
请帮忙
我尝试了很多,但我无法在 Android 上解析此文件
<?xml version="1.0" encoding="utf-8" ?>
<book>
<season id="1" name="one">
<page id="1-1" text="Page content 1" />
<page id="1-2" text="Page content 2" />
<page id="1-3" text="Page content 3" />
</season>
<season id="2" name="two">
<page id="2-1" text="Page content 1" />
<page id="2-2" text="Page content 2" />
<page id="2-3" text="Page content 3" />
<page id="2-4" text="Page content 4" />
<page id="2-5" text="Page content 5" />
<page id="2-6" text="Page content 6" />
</season>
<season id="3" name="three">
<page id="3-1" text="Page content 1" />
<page id="3-2" text="Page content 2" />
<page id="3-3" text="Page content 3" />
<page id="3-4" text="Page content 4" />
<page id="3-5" text="Page content 5" />
<page id="3-6" text="Page content 6" />
</season>
</book>
这是我的代码: 我的班级名称是 XmlReader 我在 onCreate() 方法中使用这个类
public class XmlReader
{
List<Season> Seasons;
private Season season;
private String text;
public XmlReader()
{
Seasons = new ArrayList<Season>();
}
public List<Season> getSeasons() {
return Seasons;
}
public List<Season> parse(InputStream is){
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT)
{
String tagname = parser.getName();
switch (eventType)
{
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("season"))
{
season = new Season();
season.setSeason_id( (Integer.parseInt(parser.getAttributeValue(0)) ) );
season.setSeason_name( parser.getAttributeValue(1) );
}
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("season"))
{
seasons.add(season);
}
else if (tagname.equalsIgnoreCase("page"))
{
season.setPage_id(Integer.parseInt(parser.getAttributeValue(0)));
season.setPage_text( parser.getAttributeValue(1) );
}
break;
default:
break;
}
eventType=parser.next();
}
}
catch (XmlPullParserException | IOException e)
{
e.printStackTrace();
}
return season;
}
}
【问题讨论】:
-
你用什么解析的?
-
显示你的代码你尝试了什么
-
@mohammadkiani 发布您的代码,
-
I tried a lot显示究竟如何,我们将帮助修复它。您不应该要求完整的代码,我们只能帮助修复您的代码。 -
请将您的代码添加到问题中。不是您的代码的链接。它对我不起作用。
标签: android xml xml-parsing