XML内容如下:
<students>
<student>
<name>tom</name>
<age>19</age>
</student>
<student>
<name>john</name>
<age>19</age>
</student>
<count>40</count>
<action name="swim" score="30"></action>
</students>
使用jdom解析该XML的代码如下
InputStream in = null;
Map<String, String> map = new HashMap<String, String>();
try
{
in = new FileInputStream("resource/aa.xml");
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
// 获取班级人数
String count = root.getChild("count").getValue();
System.out.println(count);
// 获取活动
Element actionEle = root.getChild("action");
String actionName = actionEle.getAttribute("name").getValue();
String score = actionEle.getAttribute("score").getValue();
Action action = new Action(actionName, score);
System.out.println(action);
// 获取学生信息
List<Element> eles = root.getChildren("student");
String name = "";
String value = "";
for (Element el : eles)
{
name = el.getChild("name").getValue();
value = el.getChild("age").getValue();
map.put(name, value);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
System.out.println(map);
}
结果为:
40
name=swim; score=30
{john=19, tom=19}
附:
String转InputStream
String aa = "dd";
InputStream is = new ByteArrayInputStream(aa.getBytes());
本文通过使用jdom库解析XML文件,演示了如何获取XML中的班级人数、活动信息及学生个人信息。包括读取XML文件、解析节点、获取属性值、遍历学生列表并收集数据。
289

被折叠的 条评论
为什么被折叠?



