我想解析本地XML文件,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<categories>
<category>
<id>1</id>
<name>Main name</name>
<subcategories>
<count>1</count>
<subcategory>
<id>2</id>
<name>Sub name</name>
<products>
<count>5</count>
<product>
<id>1</id>
<name>fullname</name>
<description>this is full name and something</description>
<color>white</color>
<size>xyz</size>
<images>
<count>2</count>
<image>
<title>test</title>
<url>www.test.com/test1.jpg</url>
</image>
</images>
</product>
</products>
</subcategory>
</subcategories>
</category>
<category>
<id>2</id>
<name>other name</name>
<subcategories>
<count>1</count>
<subcategory>
<id>2</id>
<name>other name subname</name>
<products>
<count>5</count>
<product>
<id>1</id>
<name>patname of othername</name>
<description>this isapt name and something</description>
<color>white</color>
<size>xyz</size>
<images>
<count>2</count>
<image>
<title>test</title>
<url>www.test.com/test1.jpg</url>
</image>
</images>
</product>
</products>
</subcategory>
</subcategories>
</category>
</categories>
如何在Android中解析这个本地XML文件,如何在标签类别中使用它的内部标签,如果它具有id 1和2,那么如果类别的id是1而不是print或者用户,那么它的所有内部标签内容都是类别等。如何在Android中使用这两个类别的内部标记的内容?
答案 0 :(得分:0)
解析很简单,并且在所有应用程序中都相同,使用SAX解析器的任何示例或任何其他样本来简单地解析XML。 无论是否为Android,您都不必担心所使用的平台!
public class AttendanceXMLParser {
public static final String STUDENT_ATTENDANCE = "student_attendance";
public List<Attendance> parseXML(String xml) {
List<Attendance> attendanceList = new ArrayList<Attendance>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document document = dBuilder.parse(is);
NodeList attendanceNodeList = document.getElementsByTagName(STUDENT_ATTENDANCE);
int nodeListLength = attendanceNodeList.getLength();
Attendance attendance = null;
for(int i=0; i<nodeListLength; i++) {
attendance = new Attendance();
Node messageNode = attendanceNodeList.item(i);
//
attendance.setStudentName(messageNode.getFirstChild().getTextContent());
attendance.setCourseName(messageNode.getChildNodes().item(1).getTextContent());
attendance.setSemester(messageNode.getChildNodes().item(2).getTextContent());
attendance.setAttendance(messageNode.getChildNodes().item(3).getTextContent());
attendanceList.add(attendance);
}
return attendanceList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
请找到代码,它实际上根据节点student_attendance解析简单的出勤列表,并且该函数生成一个学生出勤列表,仔细阅读代码,这可能对你有所帮助!!
答案 1 :(得分:0)
答案 2 :(得分:0)
不,不,在这种情况下不能使用SAXParser,因为许多标签具有相同名称......最好使用XPath
:http://developer.android.com/reference/javax/xml/xpath/package-summary.html